Dimitri
Dimitri

Reputation: 8280

Conditional form validation with Yup

I am beginner in Yup and I need to do some form validation with Yup. Here is an example of my schema :

    const MyFormSchema = Yup.object().shape({
       contactId: Yup.string().required(),
       phoneNumber : Yup.string().phoneNumber().required(),
       email: Yup.string().email().required()
    });

My form is valid in 2 cases : either the user enters the contactID or he enters the phoneNumber and the email.

I tried to implement this using test function but was unable to do it. Any help would be appreciated.

Upvotes: 1

Views: 2314

Answers (1)

demkovych
demkovych

Reputation: 8827

You can build the same logic for rest 2 fields:

Yup.object().shape({
    contactId: Yup.string().when(["phoneNumber", "email"], {
      is: (phoneNumber, email) => !phoneNumber || !email,
      then: Yup.string().required()
    }),
    phoneNumber: Yup.string().when("contractId", {
      is: contactId => !!contactId,
      then: Yup.string().required()
    }),
    email: Yup.string().when("contractId", {
      is: contactId => !!contactId,
      then: Yup.string()
        .email()
        .required()
    })
});

To check for email, you can use built in function Yup.email(). For phone you need to build custom validator:

const PHONE_VALIDATOR = /...your RegEx here.../

...
phoneNumber : Yup.string().matches(PHONE_VALIDATOR, 'Phone is not valid').required()

Upvotes: 2

Related Questions