Skip to main content

Command Palette

Search for a command to run...

Yup validate array fields conditionally with Example

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

Published
2 min read
Yup validate array fields conditionally with Example
G

A company founded back in 2019 by two visionary Engineers to create and provide you with the best results possible. We are a web developing company with great vision and plans for the future to be a part of others success. We understand that you have deadlines and reputation to keep... so we will meet ours! You can rely on Ghanshyam Digital To handle your job expertly every time.

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

More from this blog

G

Ghanshyam Digital

33 posts

A Software Company delivering Softwares, Web Applications, Mobile Applications using latest technologies.