Siddharth
Siddharth

Reputation: 944

Java Script Regular expression for number format not working

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?

Upvotes: 0

Views: 70

Answers (4)

monojit biswas
monojit biswas

Reputation: 147

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

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

Upvotes: 0

Bharat Ranpariya
Bharat Ranpariya

Reputation: 1253

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.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174844

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.

Upvotes: 1

anubhava
anubhava

Reputation: 786136

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.

Upvotes: 0

Related Questions