0

I'm trying to create a regular expression using javascript for react application that allow negative and positive decimal numbers and not allow enter any character.

I've been looking for examples, reading documentation but I dont know how make it.

This are the things that have to do:

allow negative and positive decimal numbers, I found this:

var re = new RegExp("^[+-]?[0-9]{0,900}(?:\.[0-9]{0,900})?$");

but I can write a character and show me true and add other character and show me false. console.log(re.test(value));

if is decimal and starts with zero show zero (0.232) and dont allow this (.232)

dont allow write characters, I've seen this /^\d*$/

Tushar
  • 85,780
  • 21
  • 159
  • 179
Javier
  • 1,975
  • 3
  • 24
  • 46

2 Answers2

2

Looking at the documentation about RegExp it states that when using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.

Your regex would then match a dot which would match any character making for example a valid because the preceding [0-9]{0,900} matches zero - 900 times.

Your regex would become:

var re = new RegExp("^[+-]?[0-9]{0,900}(?:\\.[0-9]{0,900})?$");

To match negative and positive decimal numbers that should not start with a dot, you could use:

^[+-]?[0-9]+(?:\.[0-9]+)?$

Which will match the beginning of the string ^, an optional [+-]?, one or more digits [0-9]+ followed by an optional part which will match a dot and one or more digits (?:\.[0-9]+)? and then the end of the string $.

var re = new RegExp("^-?[0-9]+(?:\\.[0-9]+)?$");

var re = new RegExp("^[+-]?[0-9]+(?:\\.[0-9]+)?$");
var strings = [
  "1",
  "1.2",
  "0.232",
  ".232",
  "-1.2",
  "+1.2"

];

strings.forEach((s) => {
  console.log(s + " ==> " + re.test(s));
});
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • look here https://regex101.com/r/OREez0/1, in your function works but using react onChange doesnt work – Javier May 03 '18 at 09:36
  • @JaviLesPaul Perhaps [this page](https://stackoverflow.com/questions/40883057/use-regular-expression-in-jsx-file-in-react-material-ui) can be helpful. – The fourth bird May 03 '18 at 13:44
0

I use this:

^-?[0-9]\d*(\.\d+)?$
  • only numbers
  • positive and negative
  • dont allow .232