Reactjs 是的
我有一个有两个输入的表单,一个是选择一个国家,另一个是文本输入字段,它根据在选择项上选择的国家获取验证模式(EU tax regex) 我正试图使用yup实现这一点,但不知道如何访问yup中另一个字段的值Reactjs 是的,reactjs,formik,yup,Reactjs,Formik,Yup,我有一个有两个输入的表单,一个是选择一个国家,另一个是文本输入字段,它根据在选择项上选择的国家获取验证模式(EU tax regex) 我正试图使用yup实现这一点,但不知道如何访问yup中另一个字段的值 const taxIdValidation = { AT: '(AT)?U[0-9]{8}', BE: '(BE)?0[0-9]{9}', BG: '(BG)?[0-9]{9,10}', CY: '(CY)?[0-9]{8}L', CZ: '(CZ)
const taxIdValidation = {
AT: '(AT)?U[0-9]{8}',
BE: '(BE)?0[0-9]{9}',
BG: '(BG)?[0-9]{9,10}',
CY: '(CY)?[0-9]{8}L',
CZ: '(CZ)?[0-9]{8,10}',
DE: '(DE)?[0-9]{9}',
DK: '(DK)?[0-9]{8}',
EE: '(EE)?[0-9]{9}',
GR: '(EL|GR)?[0-9]{9}',
ES: '(ES)?[0-9A-Z][0-9]{7}[0-9A-Z]',
FI: '(FI)?[0-9]{8}',
FR: '(FR)?[0-9A-Z]{2}[0-9]{9}',
GB: '(GB)?([0-9]{9}([0-9]{3})?|[A-Z]{2}[0-9]{3})',
HU: '(HU)?[0-9]{8}',
IE: '(IE)?[0-9]S[0-9]{5}L',
IT: '(IT)?[0-9]{11}',
LT: '(LT)?([0-9]{9}|[0-9]{12})',
LU: '(LU)?[0-9]{8}',
LV: '(LV)?[0-9]{11}',
MT: '(MT)?[0-9]{8}',
NL: '(NL)?[0-9]{9}B[0-9]{2}',
PL: '(PL)?[0-9]{10}',
PT: '(PT)?[0-9]{9}',
RO: '(RO)?[0-9]{2,10}',
SE: '(SE)?[0-9]{12}',
SI: '(SI)?[0-9]{8}',
SK: '(SK)?[0-9]{10}'
};
const validationSchema = yup.object().shape({
taxIdentificationNumbers: yup
.array()
.of(
yup.object().shape({
country: yup.string().nullable(),
vatValue: yup
.string()
.nullable()
.when('country', {
is: value => value && value.length > 0,
then: yup
.string()
.matches(taxIdValidation[value])
.required('Tax ID is required.')
})
})
)
.nullable()
});
我有一个taxIdValidation对象,然后基于country alphaCode2的值,我想将regex设置为同一个键。但是,在这种语法中,我无法访问countries值
如果有人知道如何解决这个问题,我很乐意听到。您可以使用
test
来获取父级或同级值:
const validationSchema = yup.object().shape({
taxIdentificationNumbers: yup
.array()
.of(
yup.object().shape({
country: yup.string().nullable(),
vatValue: yup
.string()
.nullable()
.when('country', {
is: value => value && value.length > 0,
then: yup
.string()
.test('tax validation', 'Wrong tax format', function (value) {
const { country } = this.parent;
return value.match(taxIdValidation[country]);
})
.required('Tax ID is required.')
})
})
)
.nullable()
});
未处理的拒绝(TypeError):无法读取未定义的属性“match”。测试方法中的字符串代表什么?只需要一点检查,不要破坏我的应用程序。太棒了,谢谢你了,伙计!