Javier
Javier

Reputation: 2095

Regular Expression for negative and positive decimal numbers

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

Answers (2)

The fourth bird
The fourth bird

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:

^[+-]?[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));
});

Upvotes: 2

Matias Pons
Matias Pons

Reputation: 3

I use this:

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

Upvotes: 0

Related Questions