Yup validate array fields conditionally with Example

Yup validate array fields conditionally with Example

yup library conditional validation of array and/or it's fields

Play this article

When working with complex data structures and forms, validating specific fields conditionally becomes crucial. In this scenario, I encountered the need to validate fields within an array based on the value of another boolean field. Let's take a closer look at the situation and the solution.

Form Schema Overview:

Consider the following schema extracted from a form:

     "bankAccounts": [
          "accountType": "savings",
          "accountNumber": "11111111111",
     "bankingEnabled": true

In this structure, we have an array of bank accounts, each containing an account type and account number. Additionally, there's a boolean field bankingEnabled indicates whether banking is enabled.

Conditional Validation Approach:

The objective is to validate the array fields only if the bankingEnabled flag is set to true. Achieving this using a robust validation library like Yup involves defining a schema that adapts based on this condition.

Here's an example of how you can achieve this using the Yup validation library:

// Defining the conditional validation schema
const bankAccountSchema = yup.object().shape({
  accountType: yup.string().required('Please select your Account Type'),
  accountNumber: yup
    .required('You must enter an Account Number')
    .matches(/^[0-9]+$/, 'Must consist of digits only')
    .min(5, 'Must be at least 5 digits')
    .max(17, 'Must not exceed 17 digits')

const schema = yup.object().shape({
  bankAccounts: yup.array().when('bankingEnabled', {
    is: true,
    then: yup.array().of(bankAccountSchema)
  bankingEnabled: yup.boolean()

In this schema, we use the .when method to conditionally apply validation rules to the bankAccounts array field. If bankingEnabled is true, the array is validated against the bankAccountSchema. Otherwise, it's considered valid without any constraints.

Final Thoughts:

By strategically implementing conditional validation through libraries like Yup, you can ensure that your forms remain intuitive and error-free while accommodating complex conditions. This approach enhances user experience and data accuracy, contributing to the overall effectiveness of your application.

We hope this guide has shed light on the process of conditionally validating array fields based on boolean values. As you navigate similar challenges in your development journey, remember that adaptable validation practices are key to maintaining robust and user-friendly applications.

Did you find this article valuable?

Support Ghanshyam Digital by becoming a sponsor. Any amount is appreciated!