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

IT技术 reactjs formik yup
2021-05-16 05:06:51

我正在做一个 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开发人员工具抱怨未捕获的Promise时:

在此处输入图片说明

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

1个回答

您可以使用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"),
});