While writing some code for a shopping cart, I found myself with the need to validate a text input field as US currency. Greenbacks. Dolla Dolla bills y'all. $$$

Any of the following inputs from the user should be valid:

1.00 || 0 || 0.01 || .20 || .4

And, all of these should be invalid:

1a.00 || -1.23 || 9.&8 || 0.0h

This could obviously be done on the back end, but come on, this is web 2.0! Javascript to the rescue.

I did a quick search, and found this hilarious script. It just seemed like total overkill; 6.82kb just to check if a text input is valid US currency! There had to be a better/more efficient way.

And then it dawned on me: regular expressions, duh! So here is what I came up with.

var RegExp = /^(\d*)(\.\d{0,2})?$/;
result = someTextInput.match(RegExp);

In two lines of code, this accomplishes most of what that huge script does.

It looks for:

  • -0 or more digits
  • -followed by 0 or 1 instances of a decimal point with 2 or less digits after

I don't care about checking for dollar signs ($) or commas (,) so I don't.

You can throw the two lines of js into a little function and call it on the text input's onKeyUp.

Here is a sample.

Just type and it will tell you the results.

$


COMMENTS / 2 COMMENTS

69,696.96 doesn’t work

Benson added these pithy words on Nov 05 07 at 9:51 pm

Right, in the article it mentions that I don’t want commas.

It is very easy to mod the regex to look for a digit* comma digit* pattern.

admin added these pithy words on Nov 05 07 at 10:09 pm

SPEAK / ADD YOUR COMMENT
Comments are moderated.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Return to Top