Conditional validation with Yup and Formik

夙愿已清 提交于 2020-04-11 03:54:52

问题


Here is my validation schema:

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')
      })
    });

And also there are two variables in React State: isPerson and isCompany. How to make validation work conditionally, for example if isPerson is true, then person in validationSchema is required to be validated?


回答1:


You can conditionally add to your validation schema just like any other object:

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);



回答2:


you can use Yup conditions

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()
      }),
    });


And make sure to update your form accordingly. I hope you get the point...



来源:https://stackoverflow.com/questions/54919228/conditional-validation-with-yup-and-formik

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!