【问题标题】:How to get Yup to perform more than one custom validation?如何让 Yup 执行多个自定义验证?
【发布时间】:2020-12-25 09:04:43
【问题描述】:

我正在开发一个 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 根据我检测到的验证失败给我一个不同的错误字符串?

【问题讨论】:

标签: reactjs formik 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"),
});

【讨论】:

  • 谢谢,我试过了,但由于某种原因,如果我有多个 addMethod,我会收到问题中提到的相同 Promise 错误。我很好奇 createError 返回什么?也许我可以组合多个addMethod,但只使用if语句来选择合适的错误信息?
  • 嗨@John,createError 函数返回一个ValidationError 对象,这是来自Yup 的错误。当您进行测试时,它可以返回 true、false 或 ValidationError。正如您所说,您可以使用此错误和一些 if 语句在同一方法中验证多个案例,如果一切顺利,最后返回true!还有一个小技巧,这种情况下不要使用箭头函数,你需要this不绑定。
  • 如果有 credirCardType 错误,它不会抛出 is required 错误,即如果我输入空数据,而不是抛出 required 错误,它仍然会抛出 creditCard 错误
  • 是的,在这一行中我正在这样做:return ( getCardType(value).length > 0 || createError({ path, message: errorMessage }) ); 但如果长度为零,您可以使用 >= 0 返回 true 并允许链中的下一个测试运行并验证有需要的情况。
猜你喜欢
  • 1970-01-01
  • 2020-11-05
  • 2015-07-20
  • 2020-04-24
  • 2020-02-05
  • 2016-11-16
  • 1970-01-01
  • 2021-03-19
  • 2020-05-22
相关资源
最近更新 更多