Reputation: 91
I have to validate the 'description' field when 'gender' field value is others or female but when it is male no validation required for the 'description' field.
First I want to show this code and this is valid and working:
description: Yup.string().when(['gender'], {
is: (gender) => gender=== 'others',
then: Yup.string().required('Description is Required')
})
But Now I have to use multiple conditions like this:
description: Yup.string().when(['gender'], {
is: (gender) => gender=== 'others' || 'female' ,
then: Yup.string().required('Description is Required')
})
But It's not working. Please Give me a solution. Thanks in advance...
Upvotes: 7
Views: 23502
Reputation: 117
// in the context variable you get the full object and retrieve your value from here
.test('DOB', "Single condition error here", (value, context) => {
const { parent } = context;
// formatted date passing the formatted the date
const formatedDate = moment(value).format('YYYY/MM/DD');
// calculateBirthYear is a custom function for getting age calculated
const selectedAge = calculateBirthYear(formatedDate);
if (parent?.role == "3") {
if (selectedAge >= 21 && selectedAge <= 45)
return true
} else if (parent?.role == "4") {
if (selectedAge >= 18 && selectedAge <= 40)
return true
} else if (parent?.role == "5") {
console.log("LINE NO 138 ", parent.role, selectedAge);
if (selectedAge >= 18 && selectedAge <= 40)
return true
}
return ctx.createError({ message: parent?.role == "3" ? Strings.sm_register.Surrogate_Mother_error : parent?.role == "4" ? Strings.sm_register.Egg_Donar_error : Strings.sm_register.Sperm_Donar_error });
}),
Upvotes: -1
Reputation: 206151
Equality operation is evaluated first.
is: (gender) => gender === 'others' || 'female' , // Not good
becomes:
is: (gender) => (Boolean) || 'female',
where if <Boolean>
is true
you'll get true
as result,
and if <Boolean>
is false
you'll get "female"
as result.
SOLUTION:
Instead, use /^(others|female)$/.test(gender)
or ['others','female'].includes(gender)
as suggested by @evolution
is: (gender) => /^(others|female)$/.test(gender) ,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
or if you want to make it long and explicit:
is: (gender) => gender === "others" || gender === "female" ,
Upvotes: 5