4

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.

1
  • 1
    If you're using a regular expression to validate the input, there is no need for a key event listener. You only need to validate the input when the user has finished entering characters, until then you really don't care what the value is (e.g. the user may copy and paste from elsewhere, then edit what they pasted). Commented Aug 14, 2012 at 3:45

3 Answers 3

12

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Don't you need ^ and $ to make sure there isn't junk on the ends?
Use "d{0,2}" to allow values like "1.".
1
/^(\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

4 Comments

Wouldn't this match an empty string as well?
It would, but it also allows more common entries like .25, or 1.2, rather than forcing 0. at the beginning. Do you have any suggestions on how I could force a minimum character limit while keeping the flexibility?
You basically have two patterns (1.0 and .0) to worry about, so I had to break the regex down into essentially two separate regex patterns separated by an |.
Ah, I see, that is a rather good way to do it. I hadn't thought of that. I need to brush up on my regex more often
1

I used the comma for decimal separator. Here my friends:

^([0]?(,\d{1,2})?|([1-9]{1,3})?((\.\d{3})*|([1-9])*)?(,\d{1,2})?)?$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.