最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Yup validate number only, avoide e, E, -, + characters - Stack Overflow

programmeradmin1浏览0评论

I'm new here. I have an issue with Yup validation. I want client enter number only from 0-9, without entering e, E, +, - characters. I have code like this but user still can enter e, +, -. Is there any way to avoide these characters?

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

I try with string().matches(regex) but it still showing err with negative values. Is there the best way to use .number() without these characters?

I'm new here. I have an issue with Yup validation. I want client enter number only from 0-9, without entering e, E, +, - characters. I have code like this but user still can enter e, +, -. Is there any way to avoide these characters?

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

I try with string().matches(regex) but it still showing err with negative values. Is there the best way to use .number() without these characters?

Share Improve this question edited Nov 7, 2022 at 4:40 Pam asked Nov 7, 2022 at 4:06 PamPam 151 gold badge1 silver badge4 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You can add a custom validator with the test method:

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())
  );
发布评论

评论列表(0)

  1. 暂无评论