f4a19914 f284 43d9 bc45 8ee030552e4c

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.

Source: https://www.codementor.io/shyammakwana/yup-validate-array-fields-conditionally-24vdins6cv