1

I need users to enter an amount and this may come in different formats like 500 or 500.00. So I need to check if the user has entered a number or a number with two decimal points. SO far I have tried

if(/^\d+$/.test(amount) === false || /[0-9]+(\.[0-9][0-9]?)?/.test(amount) === false){
          //valid
}else{
         //invalid
}

But so far only the one to check if it is a number is working fine.

1
  • 1
    You want to check that either one of the checks pass, right? Change the falses to true. Commented May 4, 2013 at 17:02

1 Answer 1

7

I guess you are looking for this

var pattern=/^\d+(\.\d{2})?$/;
if(pattern.test(amount))
{
          //valid number pattern
}
else
{
         //invalid number pattern
}

\d+(\.\d{2})?$ would match 1 to many digits optionally followed by two decimal values..

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

2 Comments

Save CPU energy: use an assertion instead of capturing: /^\d+(?:\.\d{2})?$/ ;)
@meze nice suggestion..but this is too small footprint for any cpu..:)

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.