Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop yup validation on disabled fields?

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')
})
like image 828
user12440719 Avatar asked Nov 01 '25 04:11

user12440719


2 Answers

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()
  }),
})
like image 89
Reza Hashemi Avatar answered Nov 03 '25 18:11

Reza Hashemi


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(...)
like image 34
egor.xyz Avatar answered Nov 03 '25 19:11

egor.xyz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!