-1

I want to validate phone Number in the format X-XXX-XXX-XXXX

    var phone= prompt("Enter phonenumber in the format X-XXX-XXX-XXXX");
    var regEx= /\d-[\ddd\-]{2}\d{4}/; 
    if(regEx.test(phone))
    {document.write("Is valid PhoneNumber "+phone);}
    else{
     var msg= "Chaphert 6 exmaple 2a says <br/>" +phone +" is invalid";
     alert(msg);
    }

I could have used regEx=/\d-\d{3}-\d{3}-\d{4},which will solve my problem but since I have to repeat this xxx-xxx-,ie I don't wish to repeat \d{3}- twice in the regex, expecting something to replace for \d{3}-\d{3}- with something like, [\d{3}-]{2}. I would appreciate any help.

Manoj
  • 327
  • 1
  • 11
  • 2
    how about `^\d(-\d{3}){3}\d$` ? – Pruthvi Raj Jul 31 '16 at 14:06
  • What is `[\ddd\-]` supposed to mean? Did you look at this regexp on a regexp testing site? Do you know the difference between `[]` (character sets) and `()` groups? Anyway, your original regexp is much clearer and there's no reason to fiddle with it further. –  Jul 31 '16 at 14:38
  • Why don't you want to repeat the `\d{3}`? That makes it clear what the underlying structure you are trying to match actually is. It is easier to read and maintain. –  Jul 31 '16 at 14:57

3 Answers3

2

The following regex should do what you ask:

^\d(?:-\d{3}){3}\d$

DEMO

Pruthvi Raj
  • 3,016
  • 2
  • 22
  • 36
0

If you want a pattern that shows the 1-3-3-4 structure and want to prevent to use

'-\d{3}'

twice, you could put this part into a group and repeat it twice.

The final pattern would look like this then:

'^\d-(\d{3}-){2}\d{4}$'
Rafael Albert
  • 445
  • 2
  • 8
0

Thanks for your help i need to replace [] with () for grouping ie

    var phone= prompt("Enter phonenumber in the format X-XXX-XXX-XXXX");
    var regEx= /\d-(\d{3}\-){2}\d{4}/; 
     if(regEx.test(phone))
      {alert("Is valid PhoneNumber "+phone);}
     else{
     var msg= "Entered phone number " +phone +" is invalid";
     alert(msg);
     }

solved my problem, it worked as expected

Manoj
  • 327
  • 1
  • 11