JavaScript validation: regex to validate numbers with comma
How do I use JavaScript regex to 开发者_如何学运维validate numbers like this?
- 1,000
- 1,000.00
- 1000.00
- 1000
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.
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.
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 );
try this
var number = '100000,000,000.00';
var regex = /^\d{1,3}(,?\d{3})*?(.\d{2})?$/g;
alert(regex.test(number));
精彩评论