如何让Yup执行多个自定义验证?

问题描述

我正在研究ReactJS项目。我正在学习将Yup用于FormIk的验证。以下代码可以正常工作:

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评论时,开发人员工具便抱怨未实现的承诺:

enter image description here

如何根据我检测到的验证失败让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`,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"),});

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...