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')
})
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')
})
Share
Improve this question
edited Jun 20, 2020 at 9:12
CommunityBot
11 silver badge
asked Nov 26, 2019 at 20:13
user12440719user12440719
411 gold badge1 silver badge2 bronze badges
3 Answers
Reset to default 15Set 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(...)
Alternative method :
Two Fields :
- department ---> Boolean
- clinic ----> String
const validationSchema = Yup.object().shape({
department: Yup.boolean(),
clinic: Yup.string().test(
"conditionalRequired",
"Field is required",
function (value) {
const { department } = this.parent;
if (department === true) {
return !!value;
}
return true;
}
),
});
Here yup will validate the clinic field only when department is enabled.