views:

129

answers:

5

I'm doing Javascript validation on my number fields. I'm using RegEx to do this - first time RegEx user. I need the user to only enter numbers and decimals, but not commas. (i.e. 3600.00 is okay, but 3,600.00 is not). I can't figure out how to eliminate the commas as an accepted character. Any help is appreciated. Thanks!

                        var filter = /^([0-9])/;

                            if (!filter.test(txtItemAmount.value)) 
                            {
                                msg += "Item amount must be a number.\n";
                                txtItemAmount.focus
                            }       
A: 

Your filter should be something like [0-9. ]+ (here you allow numbers, . and space

A better filter would be [0-9 ]*[ .][0-9 ]* where you allow . only once.

I don't know about regex in javascript, so you may need to protect some characters with \.

Moons
A: 

try this:

^(\d+(\.\d*)?)$

It looks for one or more digits (\d+) and then, for a period followed by 0 or more digits ((\.\d*)?) . The question mark means that there has to be either 1 or 0 repetitions of the period and more digits part. THe period (.) is a special character in regex, so it has to be escaped, hence the \ before hand.

For more information, you might want to take a look here

npinti
The OP's comment said `.05` is valid, but this regex doesn't match it. It *does* match `123.`, which I would call invalid (but the OP didn't mention that one).
Alan Moore
+1  A: 

If you want to allow decimals less than 1, integers or integers with a decimal part, you can write a reg exp for that-

/^(\.\d+)|(\d+(\.\d+)?)$/.test(value)

or you can use parseFloat-

if(parseFloat(value)+''===value)
kennebec
A: 

Using "lookaround," a combo of negative lookbehind and look ahead, you should be able to fail the match if a comma is present:

(?<!,)[0-9\.]*(?!,)
Brent Arias
Among many other invalid inputs, this will match the `2` in `,123,`. Lookarounds are a little trickier than you might expect, and they're no use at all in this case.
Alan Moore
A: 
^(\d+\.?|\d*\.\d+)$

will allow 1, .2, 3., 4.5, 12345.67890 and so on; it will disallow 1,000, 0.123,456, . or 1.2.3.

Tim Pietzcker