只验证数字,避免e、e、-、+字符



我是新来的。我对Yup验证有一个问题。我希望客户端只从0-9输入数字,而不输入e, E, +, -字符。我有这样的代码,但用户仍然可以输入e, +, -。有什么方法可以避免这些字符吗?

Yup.number()
  .typeError("Please enter number value only")
  .nullable()
  .notRequired()
  .min(0)
  .max(100)
  .moreThan(-1, "Negative values not accepted")

我尝试用string().matches(regex),但它仍然显示错误与负值。有没有最好的方法来使用.number()没有这些字符?

您可以使用test方法添加自定义验证器:

Yup
  .number()
  .nullable()
  .notRequired()
  .min(0)
  .max(100)
  .test(
    "noEOrSign", // type of the validator (should be unique)
    "Number had an 'e' or sign.", // error message
    (value) => typeof value === "number" && !/[eE+-]/.test(value.toString())
  );

最新更新