0

I want to get the input from the user as 888-999-6666..i.e. 3 numbers then a '-' then 3 numbers then again '-' and finally 4 numbers. I am using the following regular expression in my JavaScript.

     var num1=/^[0-9]{3}+-[0-9]{3}+-[0-9]{3}$/;
  if(!(form.num.value.match(num1)))
           {
           alert("Number cannot be left empty");
           return false;
           }

But its not working. If I use var num1=/^[0-9]+-[0-9]+-[0-9]$/; then it wants at least two '-' but no restriction on the numbers.

How can i get the RE as my requirement? And why is the above code not working?

2
  • var num1=/^[0-9]{3}+-[0-9]{3}+-[0-9]{3}$/; typo near last symbol class? Did you mean {4}? Commented Nov 6, 2014 at 10:44
  • 1
    @SergeyLagutin + after {} acts like a possessive quantifier which was supported by php but js won't Commented Nov 6, 2014 at 10:50

4 Answers 4

1

Remove the + symbol which are present just after to the repetition quantifier {} . And replace [0-9]{3} at the last with [0-9]{4}, so that it would allow exactly 4 digits after the last - symbol.

var num1=/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;

DEMO

You could also write [0-9] as \d.

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

Comments

0

Your regex should be:

var num1=/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;

There is an extra + after number range in your regex.

Comments

0

Issue in your regex.check below example.

var num='888-999-6668';
var num1=/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
  if(!(num.match(num1)))
   {
      alert("Number cannot be left empty");
   }else{
      alert("Match");
   }

In your example there is extra + symbole after {3}, which generate issue here. so i removed it and it worked.

Comments

0
var num1=/^\d{3}-\d{3}-\d{4}$/;

I think this will work for you. The rest of your code will be the same.

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.