Conditional Validation in Yup

Conditional Validation in Yup

When it comes to form validation in JavaScript, Yup is a popular library that provides a simple and efficient way to define validation schemas. However, there are cases where we need to apply conditional validation based on certain conditions. In this blog post, we will explore different approaches to achieve conditional validation using Yup.

Approach 1: Using the when method

The when method in Yup allows us to define conditional validation based on the value of another field. We can specify the field to watch and the conditions to check. If the conditions are met, we can apply additional validation rules.

Here’s an example:

import * as Yup from 'yup';

const schema = Yup.object().shape({
  age: Yup.number().required('Age is required'),
  hasLicense: Yup.boolean(),
  licenseNumber: Yup.string().when('hasLicense', {
    is: true,
    then: Yup.string().required('License number is required'),
    otherwise: Yup.string()
  })
});

In the above code snippet, we have a form with two fields: age and licenseNumber. The licenseNumber field is only required if the hasLicense field is set to true.

Approach 2: Using the test method

If the conditional validation is more complex and cannot be achieved using the when method, we can use the test method to define a custom validation rule. This method allows us to write a function that receives the current value and the entire object being validated. We can then perform any custom logic and return a boolean value indicating the validation result.

Here’s an example:

import * as Yup from 'yup';

const schema = Yup.object().shape({
  age: Yup.number().required('Age is required'),
  hasLicense: Yup.boolean(),
  licenseNumber: Yup.string().test('conditional-validation', 'License number is required', function(value, context) {
    const { hasLicense } = context.parent;
    if (hasLicense) {
      return !!value;
    }
    return true;
  })
});

In the above code snippet, we have defined a custom validation rule for the licenseNumber field. The function checks if the hasLicense field is set to true and if the licenseNumber field has a value. If the conditions are met, the validation passes; otherwise, an error message is displayed.

These are two common approaches to achieve conditional validation in Yup. Depending on the complexity of your requirements, you can choose the most suitable approach for your use case.

Remember to install Yup using npm or yarn before using it in your project:

npm install yup

or

yarn add yup

That’s it! You now have the knowledge to apply conditional validation in Yup. Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *