Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript regex to validate a decimal before inserting into MySQL

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading