Codementor Events

Yup validate array fields conditionally

Published May 17, 2023
Yup validate array fields conditionally

So I wanted to validate few fields in array based on other boolean field. Here below is a schema of my form.

{
  "bankAccounts": [{ 
    "accountType": "savings", 
    	"accountNumber": "11111111111"
  }], 
  "bankingEnabled": true
}

Now I want that array fields to validate only if bankingEnabled is true. Here below is a Yup schema that will solve this problem:

{
  bankAccounts: yup.array()
          .when('bankingEnabled', {
            is: true,
            then: yup.array().of(
              yup.object().shape({
                accountType: yup.string().required('Please select your Account Type'),
                accountNumber: yup
                  .string()
                  .required('You must enter a Account Number')
                  .matches(/^[0-9]+$/, 'Must be only digits')
                  .min(5, 'Must be atleast 5 digits')
                  .max(17, 'Must not be more than 17 digits'),
              })
            )
          })
}

Se here's I'm checking conditionally on bankindEnabled field using when method that if value of this field is true then other validations will be executed.

Hope this helps.

Discover and read more posts from Shyam Makwana
get started
post commentsBe the first to share your opinion
Show more replies