2

How do I use JavaScript regex to validate numbers like this?

  1. 1,000
  2. 1,000.00
  3. 1000.00
  4. 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.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
da-hype
  • 21
  • 1
  • 1
  • 2

3 Answers3

3

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.

Elian Ebbing
  • 18,779
  • 5
  • 48
  • 56
3

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 );
wickedone
  • 542
  • 1
  • 6
  • 18
Larry Battle
  • 9,008
  • 4
  • 41
  • 55
2

try this

var number = '100000,000,000.00';
var regex = /^\d{1,3}(,?\d{3})*?(.\d{2})?$/g;
alert(regex.test(number));
Liviu T.
  • 23,584
  • 10
  • 62
  • 58