Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Currency format - javascript

I'm currently using the following regex to validate currency in my html input form fields:

/[1-9]\d*(?:\.\d{0,2})?/

Howevever, it is allowing the following value through: 13000.234.12

This is not a valid value. Here are valid values that I want to allow through:

VALID

125
1.25
1000.15
700.1
80.45
0.25

INVALID

130.1.4
21.......14

It feels like there should be a standard regex pattern out there for this, thoughts?

Side note: I'm preventing alphanumeric characters and dollar signs via the event key listener, so they already will not be able to be entered, which should make this problem a little easier.

like image 379
Adam Levitt Avatar asked Dec 09 '22 22:12

Adam Levitt


2 Answers

Something like this should work:

^(\d*\.\d{1,2}|\d+)$

It matches:

1.00
1
0.23
0.2
.2

It doesn't match:

.
1.1.
like image 96
Blender Avatar answered Dec 22 '22 08:12

Blender


/^(\d*?)(\.\d{1,2})?$/

So it's (Start) (Any amount of numbers only, even zero), (. and then numbers only, one or two, doesn't HAVE to be there though) End

like image 22
Gareth Parker Avatar answered Dec 22 '22 09:12

Gareth Parker