Javascript regex to validate a decimal before inserting into MySQL

Advertisements

I have a regex to validate a decimal value before inserting into MySql database, but there is an issue with it. It is allowing a just the negative symbol with no digits after it.

So for example, I’m validating against a decimal(7,2).
Here is my regex:

^[+-]?\d{0,5}(?:\.\d{0,2})?$

And here are the valid/invalid values

Valid
-1
+1 
1
+.1
-.1 
.1
+11111.11
-11111.11
11.11 
11111
+1.
-1.
1.

Invalid 
1111111
11.11111
0.111111 
.1111111
+111111.11
-111111.11
+11111.111
-11111.111
11111.111
111111.11
-
+

The problem is that it shows – and + as valid. How can I get these values to be invalid?

>Solution :

Check if there’s at least one digit at position 0 or 1 or 2 with a lookahead:

^(?=.{0,2}\d)[+-]?\d{0,5}(?:\.\d{0,2})?$

or use an alternation as in @trincot answer.

Leave a Reply Cancel reply