Reputation: 2095
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*$/
Upvotes: 0
Views: 3468
Reputation: 163352
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:
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));
});
Upvotes: 2
Reputation: 3
I use this:
^-?[0-9]\d*(\.\d+)?$
Upvotes: 0