Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery US Currency validation regEx to allow whole numbers as well

I have this regex working but now need to allow numbers without the decimal as well

// Validate for 2 decimal for money
jQuery.validator.addMethod("decimalTwo", function(value, element) {
    return this.optional(element) || /^(\d{1,3})(\.\d{2})$/.test(value);
}, "Must be in US currency format 0.99");

Currently this forces the user to at least have the .00 added to a number, would like it to allow both the current regex and whole numbers without the decimal.

would I just add the ? at the end of the second half of the RegEx?

// Validate for 2 decimal for money
jQuery.validator.addMethod("decimalTwo", function(value, element) {
    return this.optional(element) || /^(\d{1,3})(\.\d{2})?$/.test(value);
}, "Must be in US currency format 0.99");

EDIT:

Ok but what if someone enters 1.2 ?

like image 503
Phill Pafford Avatar asked May 29 '09 16:05

Phill Pafford


1 Answers

If what you want is for 1, 1.2, and 1.20 all to work:

/^(\d{1,3})(\.\d{1,2})?$/
like image 68
chaos Avatar answered Oct 29 '22 21:10

chaos