views:

168

answers:

3

I'm looking for a good way to check a number that a user has entered for correct position of an optional comma(s).

For example

1,000,000.00 = correct
1000000 = correct
1,00,000.00 = incorrect
,100,000 = incorrect

So it looks like i need to check to see that there is at least one number to the left and 3 numbers to the right of the comma. Or is there a regex way to do this?

+5  A: 
/^(?:\d+|\d{1,3}(?:,\d{3})*)(?:\.\d+)?$/
chaos
+2  A: 

What are you going to use this for? Or put another way, why care? Why not just strip out all commas and convert it to a numeric type?

Joel Coehoorn
Yeah, that's my feeling as well... this sounds suspiciously like that annoying check used by banking websites to prevent you from entering a number without two decimal places. Though i suppose if you expected some traffic from international users, checking for "10,00" might be useful prior to stripping the commas...
Shog9
I had about 1 hour to implement something in the existing validation and used something similar to the first answer above But I agree with your comment and now that I have a little bit more time to work with this is what I'm going to implement.
72Vine
+1  A: 

Check out this website: http://blog.stevenlevithan.com/archives/commafy-numbers

Here's the code snippet:

String.prototype.commafy = function () {
    return this.replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2) {
     return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
    });
}

Number.prototype.commafy = function () {
    return String(this).commafy();
}

What you can do is replace all commas and then use this code to add in the commas yourself.

Hope that helps.

Kind of a long way around for validating, but then again, why *not* go ahead and fix it? You're only validating the formatting, not the content. +1 for thinking out of the box.
Alan Moore