I have the following:
two fields: department and clinic
two radio buttons department and clinic
If the clinic radio button is checked, then the department is disabled. Now I want yup to validate the clinic field only when it is enabled. I tried something like this
// Clinic:
Yup.string().when('isDisabled', {
is: false,
then: Yup.string.required('clinic required')
})
Set three fields, for example, department, clinic and kind . The kind field is the name for radio buttons
Then set the value of each radio button like department and clinic, and your validation schema like this:
validationSchema = Yup.object().shape({
kind: Yup.string().required(),
clinic: Yup.string().when("kind", {
is: (val) => val === "clinic",
then: Yup.string().required(‘clinic required’),
otherwise: Yup.string().notRequired()
}),
department: Yup.string().when("kind", {
is: (val) => val === "department",
then: Yup.string().required(‘department required’),
otherwise: Yup.string().notRequired()
}),
})
const object = {
name: 'Foo',
hiddenOnMobileField: 'Boo'
}
// you can use any condition attribute (Ex: isMobile)
export const validationSchema = (isMobile) => yup.object().shape({
name: yup.string().trim().required('name is required'),
// this field disabled on a mobile
hiddenOnMobileField: yup.string()
// use empty array
.when([], {
// any condition to remove validation
is: () => !isMobile,
then: yup.string().trim().required('hiddenOnMobileField is required'),
otherwise: yup.string().notRequired(),
})
})
validationSchema(true).validate(object, { abortEarly: false })
.then(...)
.catch(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With