使用Yup和Formik进行条件验证

时间:2019-02-28 05:53:43

标签: javascript formik yup

这是我的验证模式:

const validationSchema = Yup.object().shape({
      person: Yup.object().shape({
        name: Yup.string().required('Field is required'),
        surname: Yup.string().required('Field is required'),
        middleName: Yup.string().required('Field is required'),
        email: Yup.string()
          .email('Wrong e-mail format')
          .required('Field is required')
      }),
      company: Yup.object().shape({
        name: Yup.string().required('Field is required'),
        address: Yup.string().required('Field is required'),
        email: Yup.string()
          .email('Wrong e-mail format')
          .required('Field is required')
      })
    });

React State中还有两个变量:isPersonisCompany。如何使验证有条件地工作,例如,如果isPerson为真,则需要验证person中的validationSchema

4 个答案:

答案 0 :(得分:1)

您可以像其他任何对象一样,有条件地将其添加到验证模式中:

let validationShape = {
  company: Yup.object().shape({
    name: Yup.string().required('Field is required'),
    address: Yup.string().required('Field is required'),
    email: Yup.string()
      .email('Wrong e-mail format')
      .required('Field is required')
  })
};

if (this.state.isPerson) {
  validationShape.person = Yup.object().shape({
    name: Yup.string().required('Field is required'),
    surname: Yup.string().required('Field is required'),
    middleName: Yup.string().required('Field is required'),
    email: Yup.string()
      .email('Wrong e-mail format')
      .required('Field is required');
}

const validationSchema = Yup.object().shape(validationShape);

答案 1 :(得分:1)

您可以使用Yup条件

const validationSchema = Yup.object().shape({

      isCompany: Yup.boolean(),
      companyName: Yup.object().when('isCompany', {
        is: true,
        then: Yup.string().required('Field is required'),
        otherwise: Yup.string()
      }),
      companyAddress: Yup.object().when('isCompany', {
        is: (companyValue) => true,//just an e.g. you can return a function
        then: Yup.string().required('Field is required'),
        otherwise: Yup.string()
      }),
    });


并确保相应地更新您的表单。我希望你明白了...

答案 2 :(得分:1)

                email: Yup.string()
                    .when([‘, 'showEmail’, ’anotherField’], {
                        is: (showEmail, anotherField) => {
                            return (showEmail && anotherField);
                        },
                        then: Yup.string().required('Must enter email address')
                    }),

也可以使用多个字段进行验证。

答案 3 :(得分:0)

虽然公认的解决方案有效,但它有一个问题 - 要验证的两个字段是通用的,必须重复。就我而言,我拥有大部分常见字段,只有 2-4 个异常值。

所以这是另一个解决方案:

  1. 分别定义每个架构 - 即 3 个架构 - commonSchema 用于公共字段,personSchema 用于个人特定字段,companySchema 用于公司特定字段。

  2. 根据状态合并模式

     const validationSchema = isPerson 
                            ? commonSchema.concat(personSchema)
                            : commonSchema.contact(companySchema)
    

有关“concat”的详细信息,请参阅 github 上的 yup docs