如何让YUP执行多个定制验证? [英] How to get Yup to perform more than one custom validation?

查看:0
本文介绍了如何让YUP执行多个定制验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个ReactJS项目。我正在学习使用YupFormIk进行验证。以下代码运行正常:

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(),

但在我取消test-num注释的那一刻,开发工具就抱怨一个未实现的承诺:

如何让YUP根据我检测到的验证失败给我不同的错误字符串?

推荐答案

您可以使用addMethod方法创建两个这样的自定义验证方法。

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"),
});

这篇关于如何让YUP执行多个定制验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆