最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin4PV0评论

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())
  );
Post a comment

comment list (0)

  1. No comments so far