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.

4
  • 1
    I think this has already been answered: stackoverflow.com/questions/3455988/… Commented Mar 28, 2011 at 7:52
  • @Elad I guess it's not the same: her we have a number where comma is the thousands separator, so 3 digits between each comma Commented Mar 28, 2011 at 8:04
  • 1
    try and give a list of unaccepted values also Commented Mar 28, 2011 at 8:14
  • Your regular expression does not test for the start and end of a string! Commented Jul 22, 2014 at 23:52

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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 );

1 Comment

With this logic, if you add a value like: 1,,4 it'll pass as True
2

try this

var number = '100000,000,000.00';
var regex = /^\d{1,3}(,?\d{3})*?(.\d{2})?$/g;
alert(regex.test(number));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.