Conditional validation with Yup and Formik
Conditional validations with YUP :
All kinds of validation that can be done with when are as follows:
1. Single value, simple condition :
RULE: Only ask for personName when isPerson true.
personName : string().when('isPerson', {
is: true,
then: Yup.string().required('Field is required'),
otherwise: Yup.string(),
})
2. Single value, complex condition :
RULE: Only ask for personName when company is "IT".
personName : string().when('company', {
is: (company)=> company==='IT',
then: Yup.string().required('Field is required'),
otherwise: Yup.string(),
})
3. Multi value, complex condition :
RULE: Only ask for personName when company is "IT" and person is valid.
personName : string().when(['company', 'isPerson'], {
is: (company,isPerson)=> company==='IT'&& isPerson,
then: Yup.string().required('Field is required'),
otherwise: Yup.string(),
})
Updated ans: 2020.
you can use Yup conditions
const validationSchema = Yup.object().shape({
isCompany: Yup.boolean(),
companyName: Yup.string().when('isCompany', {
is: true,
then: Yup.string().required('Field is required')
}),
companyAddress: Yup.string().when('isCompany', {
is: (isCompany) => 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...
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);