skip to Main Content

Having trouble nailing down this validation schema as Yup is new to me. Basically what I am looking for here is if hasCategory is true then I want at least one of the categories to be selected. Right now my schema shape is:

const validationSchema = Yup.object()
.shape({
  hasCategory: Yup.boolean().required('Yes or No must be selected for special ad category'),
  cat1: Yup.boolean(),
  cat2: Yup.boolean(),
  cat3: Yup.boolean(),
  cat4: Yup.boolean(),
});

So if hasCategory is true then I need one of cat1, cat2, cat3, or cat4 to be true. If hasCategory is false then I don’t need any of those categories to be truthy.

Any nudge in the right direction would be much appreciated!

3

Answers


  1. This should do the trick

    Yup.object()
      .shape({
        hasCategory: Yup.boolean().required(
          "Yes or No must be selected for special ad category"
        ),
        cat1: Yup.boolean(),
        cat2: Yup.boolean(),
        cat3: Yup.boolean(),
        cat4: Yup.boolean()
      })
      .test("hasCategory", "At least one category must be true", (value)=>{
        // if hasCategory is false then test passes 
        if(!value.hasCategory) return true;
        // if any one of the categories is true then test passes otherwise if all are false it fails
        return value.cat1|value.cat2|value.cat3|value.cat4
      })
    
    Login or Signup to reply.
  2. You can make use of test() method provided by Yup to perform conditional validations.

    const validationSchema = Yup.object().shape({
      hasCategory: Yup.boolean().required('Yes or No must be selected for special ad category'),
      cat1: Yup.boolean(),
      cat2: Yup.boolean(),
      cat3: Yup.boolean(),
      cat4: Yup.boolean(),
    }).test('hasCategory', 'At least one category must be selected', function(value) {
      if (this.parent.hasCategory) {
        return this.parent.cat1 || this.parent.cat2 || this.parent.cat3 || this.parent.cat4;
      } else {
        return true;
      }
    });
    

    Explination

    using test() allows you to get the value of the scheme and its context is set to the parent object giving you access to the fields. itll return true when it passes and false if it fails. theres also if hasCategory is true it checks if the others are true as well. and if its false then it just passes automatically.

    Login or Signup to reply.
  3. Use an array named catArray instead of multiple property cat1, cat2, ….

    const validationSchema = Yup.object()
    .shape({
      hasCategory: Yup.boolean().required('Yes or No must be selected for special ad category'),
      catArray: Yup.array().when('hasCategory', 
      {
         is: true,
         then: Yup.array().min(1, 'One field must be checked'), 
      })
    });
    

    I hope this way is useful.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search