15

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?

John
  • 32,403
  • 80
  • 251
  • 422
  • John did you had any issue like this one https://stackoverflow.com/questions/70316058/yup-returns-always-an-error-even-if-all-fields-are-valid ? – PanosCool Dec 12 '21 at 11:53

1 Answers1

46

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"),
});
Adrián Ferré
  • 461
  • 3
  • 5
  • Thanks I tried, but for some reason, I get the same Promise error mentioned in my question if I have more than one `addMethod`. I'm curious what does the `createError` return? Maybe I can combined multiple addMethod, but just use if statement to select the appropriate error message? – John Sep 07 '20 at 02:50
  • 1
    Hi @John, the `createError` function returns a `ValidationError` object, it's an error from Yup. When you do a test it can return true, false, or a `ValidationError`. As you say you can use this error and some if statements to validate more than one case in the same method and finally return`true` if everything goes well! One more tip, don't use the arrow function in this case, you need the `this` without binding. – Adrián Ferré Sep 07 '20 at 13:26
  • If there is credirCardType error, it doesn't throw is required error i.e If i enter empty data, instead of throwing required error, it still throws creditCard error – Sriram R Nov 20 '20 at 09:05
  • Yes, in this line I'm doing that: `return ( getCardType(value).length > 0 || createError({ path, message: errorMessage }) );` but you can use `>=` 0 to return true if the length is zero and allow the next test in the chain to run and validate there the required case. – Adrián Ferré Nov 26 '20 at 16:33