3

I have the following:

  1. two fields: department and clinic

  2. 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')
})

3 Answers 3

13

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()
  }),
})
1
  • 2
    you are the best (:
    – user7907891
    Dec 16, 2019 at 18:48
2
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(...)
0

Alternative method :

Two Fields :

  1. department ---> Boolean
  2. 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.