我有一个有两个输入的表单,一个是你选择一个国家的选择,另一个输入是文本输入字段,它获得验证方案(欧盟税收正则表达式)基于选择项目上选择的国家。
我正在尝试使用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)?[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的值,我想将正则表达式设置为相同的键。但是,在此语法中,我无法访问countries值。
如果有人知道如何解决这个问题,我会很高兴听到的。
发布于 2020-06-24 21:47:39
您可以改用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()
});https://stackoverflow.com/questions/62556522
复制相似问题