如何使用 yup 进行验证以检查字符串最小长度、最大长度并允许为空

问题描述 投票:0回答:3
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

javascript reactjs formik yup
3个回答
3
投票

你好,你可以这样做

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));


0
投票

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

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

0
投票

全局函数,

export const minLengthValidation = (value: string | undefined, limit: number | undefined = 3) => {
  if (value && value.length < limit) {
    return false
  }

  return true
}

调用了该函数,

  nick_name: yup
    .string()
    .max(50, 'Nickname must be less than 50 characters!')
    .test('min-length', 'Nickname must be greater than  3 characters!', value => minLengthValidation(value))
    .required('Nickname is required.'),
© www.soinside.com 2019 - 2024. All rights reserved.