Regex for phone number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • user1980
    New Member
    • Dec 2009
    • 112

    #1

    Regex for phone number

    hello...

    I am trying to write regular expression for the phone numbers to be in the format..

    (000) 000-0000 and (000)000-0000
    the difference being space after brackets.
    I have used this expression and it did not work..I think I am missing a pace or brackets..unabl e to figure...
    Code:
    var phoneREX = /^\(\d\d\d\) \d\d\d-\d\d\d\d | \(\d\d\d\)\d\d\d-\d\d\d\d$/;
    this phrase does not validate both the formats..
    can somebody please tell me the correct phrase..thank you
    Last edited by gits; May 9 '10, 01:03 PM. Reason: added code tags for better separation
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    You can use the ? Character for optional matching, i.e. matching both a space and no space.

    Tip: you can use \d{3} to match 3 numbers.

    Comment

    • user1980
      New Member
      • Dec 2009
      • 112

      #3
      hello
      thank you for the response..

      I did try this but seems like it does not work...it does not valdiate anything
      Code:
       var phoneRE = /^?(\(\d{3}\)\d{3}-\d{4}|(\(\d{3}\)\s\d{3}-\d{4}))$/;
      thank you

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        The ? Character goes after the optional part (in this case space). Then you don't need the | character and all the redundant characters after it.

        Comment

        • user1980
          New Member
          • Dec 2009
          • 112

          #5
          it works now..thank you

          Comment

          Working...