简体   繁体   English

如何验证 Yup 中一个字段的多个条件?

[英]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.

相关问题 如何使用带有 yup 的反应钩子验证一个 object 中的两个字段 - How to validate the two field in one object using react hook with yup Formik 是的,如果另一个字段不为空,则验证一个字段 - Formik yup validate one field if another is not empty 使用 Yup.ref 和 .test 根据多个相关字段值验证 Yup 中的字段 - Validate Field in Yup based on multiple related field values with Yup.ref and .test 是的,如何针对其他几个变量的 function 验证一个变量? - Yup, how to validate one variable against a function of several other ones? 是的:如何验证 n 个输入文本字段只需要一个 - Yup : How to validate n input text fields only one is required 如何使用 yup 和 formik 验证表单? - How to validate a form with yup and formik? 使用Yup验证多个输入字段 - Validating multiple inputs field with Yup 如何根据 angular 6 中的条件验证输入字段 - How to validate the input field based on conditions in angular 6 如何使用 Yup 验证数字字段值? 我想检查提供的数字是否以 0.01 或 0.1 为增量 - How to validate a numeric field value in react using Yup? I want to check if the number provided is in increments of 0.01 or 0.1 如何使用 Yup 验证对象数组中至少一个 object 键具有真实值? - How to validate with Yup that in array of objects at least one of object keys has true value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM