views:

2734

answers:

2

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 ?

+1  A: 

Yes, just add a ? to the end of the second grouping to make it optional. That should work nicely.

James
one more twist, see edit
Phill Pafford
+1  A: 

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

/^(\d{1,3})(\.\d{1,2})?$/
chaos
OMG I'm so caught up in other stuff I didn't even think of this, LOL thanks
Phill Pafford