[英]How to validate multiple conditions for one field in Yup?
I am using Formik and Yup for valdiation.我正在使用 Formik 和 Yup 进行验证。 I have this validation schema and the field "listType" can have 3 values [0, 1, 2].
我有这个验证模式,字段“listType”可以有 3 个值 [0, 1, 2]。 I want to make 3 different conditions for each value of listType and put different validations based on the value
我想为 listType 的每个值创建 3 个不同的条件,并根据值进行不同的验证
const validationSchema = Yup.object().shape({
listType: Yup.string().required('Type is required'),
values: Yup.array().when('listType', {
is: (listType) => listType == 0,
then: Yup.array().of(
Yup.string()
.matches(macAdressRegex, 'Please enter valid MAC Addresses')
.required('Field is required'),
),
}),
});
I want to validate also when listType value==1 and value==2 and put different regex validation for each one of them, but I can't find a way to make it work.我还想在 listType value==1 和 value==2 时进行验证,并对它们中的每一个进行不同的正则表达式验证,但我找不到让它工作的方法。
You can use .test
function:您可以使用
.test
function:
const validationSchema = yup.object({
listType: yup.string().required('Type is required'),
values: yup.array().test('values-test', 'dummy message', (value, validationContext) => {
const {
createError,
parent: {
listType,
},
} = validationContext;
if (listType === 0 && value === 'some value') {
return createError({ message: 'listType = 1, ' + value });
}
if (listType === 3 && value === 'some value') {
return createError({ message: 'listType = 3, ' + value });
}
return true;
}),
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.