Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Yup to perform more than one custom validation?

I'm working on a ReactJS project. I'm learning to use Yup for Validation with FormIk . The following code works fine:

const ValidationSchema = Yup.object().shape({
  paymentCardName: Yup.string().required(s.validation.paymentCardName.required),
  paymentCardNumber: Yup.string()
  /*
    .test(
      "test-num",
      "Requires 16 digits",
      (value) => !isEmpty(value) && value.replace(/\s/g, "").length === 16
    )
  */
    .test(
      "test-ctype",
      "We do not accept this card type",
      (value) => getCardType(value).length > 0
    )
    .required(),

But the moment I uncomment the test-num the developer tools complain about an uncaught promise:

enter image description here

How do I get Yup to give me a different error string based on the validation failure that I detect?

like image 564
John Avatar asked Sep 06 '20 21:09

John


1 Answers

You can use the addMethod method to create two custom validation methods like this.

Yup.addMethod(Yup.string, "creditCardType", function (errorMessage) {
  return this.test(`test-card-type`, errorMessage, function (value) {
    const { path, createError } = this;

    return (
      getCardType(value).length > 0 ||
      createError({ path, message: errorMessage })
    );
  });
});

Yup.addMethod(Yup.string, "creditCardLength", function (errorMessage) {
  return this.test(`test-card-length`, errorMessage, function (value) {
    const { path, createError } = this;

    return (
      (value && value.length === 16) ||
      createError({ path, message: errorMessage })
    );
  });
});

const validationSchema = Yup.object().shape({
  creditCard: Yup.string()
    .creditCardType("We do not accept this card type")
    .creditCardLength('Too short')
    .required("Required"),
});
like image 112
Adrián Ferré Avatar answered Oct 16 '22 19:10

Adrián Ferré