Reputation: 21
How do I use JavaScript regex to validate numbers like this?
I tried this (the string used should not match):
test('2342342342sdfsdfsdf');
function test(t)
{
alert(/\d{1,3}(,\d{3})*(\.\d\d)?|\.\d\d/.test(t));
}
but still gives me true.
Upvotes: 2
Views: 10677
Reputation: 9178
I'm not sure what you mean by validate. But this might work.
//console.log is used in firebug.
var isNumber = function( str ){
return !isNaN( str.toString().replace(/[,.]/g, '') );
}
console.log( isNumber( '1,000.00' ) === true );
console.log( isNumber( '10000' ) === true );
console.log( isNumber( '1,ooo.00' ) === false );
console.log( isNumber( 'ten' ) === false );
console.log( isNumber( '2342342342sdfsdfsdf') === false );
Upvotes: 3
Reputation: 19027
If you want to test if the complete input string matches a pattern, then you should start your regex with ^
and end with $
. Otherwise you are just testing if the input string contains a substring that matches the given pattern.
^
means "Start of the line"$
means "End of the line"In this case it means you have to rewrite you regex to:
/^(\d{1,3}(,\d{3})*(\.\d\d)?|\.\d\d)$/
If you would omit the extra parentheses, because otherwise the "|"
would have lower precedence than the ^
and $
, so input like "1,234.56abc"
or "abc.12"
would still be valid.
Upvotes: 3
Reputation: 23664
try this
var number = '100000,000,000.00';
var regex = /^\d{1,3}(,?\d{3})*?(.\d{2})?$/g;
alert(regex.test(number));
Upvotes: 2