React hook form + Yup Array Validation and each item with custom validation

38 Views Asked by At

I have to an array of payment_methods. I want to validation each item with different validaiton for example. I have method_type, account number and upi handle. If method type is UPI, then upi handle is required, if its Bank and then account number is required. How can I implement this.

So far I tried various methods. Like when and then in yup but it give branch is not a function error.

1

There are 1 best solutions below

0
Vladan Djordjevic On

To implement the validation logic you described using Yup, you can make use of the .when() function to conditionally apply validations based on the value of another field. However, it's important to correctly structure your Yup schema to avoid errors like the one you encountered with .branch() not being a function, which suggests there might have been a syntax issue or a misunderstanding of the Yup API.

Below is an example of how you can structure your Yup schema to validate an array of payment methods, where each payment method requires different fields based on the method_type value:

  1. UPI method: Requires the upi_handle.
  2. Bank method: Requires the account_number.

import * as Yup from 'yup';

const paymentMethodSchema = Yup.object().shape({
  method_type: Yup.string().required('Method type is required'),
  account_number: Yup.string().when('method_type', {
    is: 'Bank',
    then: Yup.string().required('Account number is required for Bank method'),
    otherwise: Yup.string().notRequired(),
  }),
  upi_handle: Yup.string().when('method_type', {
    is: 'UPI',
    then: Yup.string().required('UPI handle is required for UPI method'),
    otherwise: Yup.string().notRequired(),
  }),
});

const paymentMethodsSchema = Yup.array().of(paymentMethodSchema);

// Example usage:
const paymentMethods = [
  { method_type: 'UPI', upi_handle: 'user@upi' },
  { method_type: 'Bank', account_number: '1234567890' },
  // Add more payment methods as needed
];

paymentMethodsSchema
  .validate(paymentMethods, { abortEarly: false })
  .then(function (valid) {
    console.log('Payment methods are valid:', valid);
  })
  .catch(function (err) {
    console.log('Validation errors:', err.inner);
  });

  • The paymentMethodSchema defines the validations for an individual payment method, using .when() to conditionally require account_number or upi_handle based on the method_type.
  • The paymentMethodsSchema is an array schema that validates each item in the array against the paymentMethodSchema.

This setup should allow you to validate each item in your array of payment methods according to the rules you've specified, without encountering the .branch() error. Remember to install Yup in your project if you haven't already, and adjust the schema as needed to fit your exact validation requirements.