最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to stop yup validation on disabled fields? - Stack Overflow

programmeradmin3浏览0评论

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

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')
})
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
Add a comment  | 

3 Answers 3

Reset to default 15

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(...)

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.

发布评论

评论列表(0)

  1. 暂无评论