admin管理员组

文章数量:1388225

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

本文标签: javascriptYup validate number onlyavoide ee charactersStack Overflow