【问题标题】:How to validate using yup to check string min length, max length and allow empty如何验证使用 yup 检查字符串最小长度、最大长度并允许为空
【发布时间】:2021-12-30 11:14:14
【问题描述】:
firstName: yup
    .string()
    .test(
        'len',
        'can be empty or with string at least 2 characters and not more than 10',
        (val) => val != undefined && (val.length == 0 || (val.length >= 2 && val.length <= 10) )
    )

在这种情况下,长度最小 2 和最大 10 有效,但是当为空时标记为错误我尝试使用 val.length == 0

【问题讨论】:

  • 我猜如果你想让该值为空 (0) 从代码中删除 val.length ==0。
  • 在字符串后添加 required() 可以解决问题
  • @TigranPetrosyan 必须允许为空
  • 不输入文字会不会val变成undefined
  • @PeterB 是的,这就是问题所在:)

标签: javascript reactjs formik yup


【解决方案1】:

通过单独的未定义检查修复

  firstName: yup
            .string()
            .test(
                'len',
                'can be empty or with string at least 2 characters and not more than 10',
                (val) => {
                    if (val == undefined) {
                        return true;
                    }
                    return  ((val.length == 0 || (val.length >= 2 && val.length <= 10)))
                }
            ),

【讨论】:

    【解决方案2】:

    你好,你可以这样做

    const yup = require("yup");
    const firstName = "";
    
    const schema = yup
      .string()
      .test(
        "len",
        "can be empty or with string at least 2 characters and not more than 10",
        (val) => {
          if (val === undefined) {
            return true;
          }
          return val.length === 0 || (val.length >= 2 && val.length <= 10);
        }
      );
    
    schema
      .validate(firstName)
      .then((response) => console.log(response))
      .catch((err) => console.log(err));

    【讨论】:

      猜你喜欢
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2023-01-30
      • 1970-01-01
      • 2017-11-15
      • 2012-06-14
      相关资源
      最近更新 更多