Solved

Need help with telephone regular expression

Posted on 2008-10-08
12
289 Views
Last Modified: 2008-10-22
I suck at regular expressions! I need help!

I need a regular expression that will validate a standard North American telephone number. It should accept the following formats:

(###) ###-####
###-####
### ###-####
### ### ####

Here's the catch. I'm using the regular expression to validate as the phone number is being typed so it needs to successfully validate along the way.

Can someone please help?
0
Comment
Question by:Russ Suter
  • 3
  • 3
  • 2
  • +3
12 Comments
 
LVL 51

Expert Comment

by:ahoffmann
ID: 22674381
here is the raw regex:

[)]?\d\d\d[) -]\d\d\d(\d|[) -]\d\d\d\d)
0
 
LVL 20

Author Comment

by:Russ Suter
ID: 22674428
It doesn't work.
0
 
LVL 16

Expert Comment

by:Lolly-Ink
ID: 22674439
This example validates while being typed. Only tested in IE7.
<html>

<style>

   *

   {

      font-family: Arial, Helvetica, sans-serif;

   }

</style>

<script>

   var _keyCode = 

   {

      VK_BACK:     0x08,

      VK_TAB:      0x09,

      VK_SUBTRACT: 0x6D,

      VK_HYPHEN:   0xBD

   };
 

   function keyDownPhone(inputPhone, evt)

   {

      evt = evt ? evt : window.event;

      var r = 

      [

         /^(\((\d(\d(\d(\)( (\d(\d(\d(-(\d(\d(\d(\d)?)?)?)?)?)?)?)?)?)?)?)?)?)?$/, // (###) ###-####

         /^(\d(\d(\d(-(\d(\d(\d(\d)?)?)?)?)?)?)?)?$/, // ###-####

         /^(\d(\d(\d( (\d(\d(\d(-(\d(\d(\d(\d)?)?)?)?)?)?)?)?)?)?)?)?$/, // ### ###-####

         /^(\d(\d(\d( (\d(\d(\d( (\d(\d(\d(\d)?)?)?)?)?)?)?)?)?)?)?)?$/ // ### ### ####

      ];

      var c = String.fromCharCode(evt.keyCode);

      switch (evt.keyCode)

      {

         case _keyCode.VK_SUBTRACT:

         case _keyCode.VK_HYPHEN:

            if (!(evt.shiftKey))

            {

               c = "-";

            }

            break;

         case _keyCode.VK_BACK:

         case _keyCode.VK_TAB:

            return true;

            break;

      }

      if (evt.shiftKey)

      {

         switch (c)

         {

            case "9":

               c = "(";

               break;

            case "0":

               c = ")";

               break;

            default:

               c = "?";

               break;

         }

      }

      for (var index = 0; index < r.length; index++)

      {

         if (r[index].test(inputPhone.value + c))

         {

            return true;

         }

      }

      event.cancelBubble = true;

      event.returnValue  = false;

      if (event.preventDefault) event.preventDefault();

      if (event.stopPropagation) event.stopPropagation();

      return false;

   }

</script>

<body onload="formTest.inputPhone.focus()">

   <form name="formTest">

      Other: <input name="inputOther" type="text"/>

      Phone: <input name="inputPhone" type="text" onkeydown="keyDownPhone(this, event)"/>

      Other: <input name="inputOther" type="text"/>

   </form>

</body>

</html>

Open in new window

0
 
LVL 18

Expert Comment

by:Hube02
ID: 22674452
You want to use a single regular expression to validate it as it is being typed?

if other words, if the user types in the number "(123) 456-7890" all of the following would validate:
(
(1
(12
(123
(123)
(123)
(123) 4
(123) 45
etc............................

What language are you running it it?
0
 
LVL 20

Author Comment

by:Russ Suter
ID: 22674482
Hube, you have correctly defined the problem. This is going to be done using Javascript.
0
 
LVL 18

Expert Comment

by:Hube02
ID: 22674950
You might want to try out Lolly-Ink's solution. The regular expressions he uses look like they will work, and these can easily be added to by following those examples if you decide to allow other variations (like ###.###.### which seems popular lately)

Unfortunately, JavaScript does not support look behind, and this would be the only way to truly validate all the possibilities with a single expression that would not grow to enormous proportions.

for instance "123)" should not validate because there is a closing parenthesis without an opening parenthesis. Similarly, you would not want it to match "123-12-1". Without a look behind there is no way to tell if there is a ( and three numbers before a ) and there is no way to tell that the correct sequence exists before the second -

although, you could concatenate them all of Lolly-Ink's into a very lengthy regular expression full of OR's

^((expression1)|(expression2)|(expression3)|(etc...))$
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 51

Expert Comment

by:ahoffmann
ID: 22676286
please describe more detailled what a "validate a standard North American telephone number" is for you
For example are following valid:
  xxx xxx.xxxx
  xxx xxxx.xxx
  xxxxxxxxxx
  xxx-xxxx
  xxxxxxx
  (xxx)xxxxxx
  (xxx) xxx-xxxx
and many, many more ...

If such numbers are valid, please describe exactly what is not valid.
0
 
LVL 20

Author Comment

by:Russ Suter
ID: 22678475
I'm mainly looking for the following 3 patterns:

(###) ###-####
### ### ####
##########

I'd like the expression to be flexible enough so that spaces and dashes are interchangeable.
0
 
LVL 16

Expert Comment

by:Bryan Butler
ID: 22679446
so, is this pseudo code it...

if typing a non-numeric except for '(', ')','-' or " "(space), then fail.  OR
if '(' is typed, and it isn't the first char, then fail OR
if ')' is typed, and it isn't preceded by '(###' then fail OR
if '-' is typed and it isn't preceded by ### then fail OR
if typing more than 10 digits fail
otherwise things are good to go

There are tons of "what ifs" and this is only considering the 3 cases you describe in general.  If you want the spaces to be verified in the right position, then that adds some more "ORs"; the '-' verified in the right place, then that's more; the spaces and dashes interchangeable, then that's even more ORs.  

Are you saying there can only be those three (with flexibility of spaces and dashes), or can it be:

### #######
(###)### #### (no space between R paren and 1st digit of LATA)
(###)#######

I guess there's not any others, but these minor differences may matter to you and others.  
0
 
LVL 10

Expert Comment

by:Hans Langer
ID: 22684286
(
 (\(\d{3}\)\s\d{3}\-)   <--- for "(###) ###"
 |
 (\d{3}\s\d{3}\s) <--- for "### ### "
 |
 (\d{6}) <-- for "######"
)
\d{4}$ <-- all condition finish wit 4 digit

Reg exp:

((\(\d{3}\)\s\d{3}\-)|(\d{3}\s\d{3}\s)|(\d{6}))\d{4}$
0
 
LVL 51

Accepted Solution

by:
ahoffmann earned 500 total points
ID: 22684756
([(]?\d{3}[)]?[ -]?\d{3}[ -]?\d{4})[^\d]?

exactly what you asked for: allowing *one* space or dash on two special positions and optional ( left oft 1st digit and ) right after 3'rd digit. () are part of the match. Only mismatch is when () are not balanced.
This regex can be used global.
0
 
LVL 16

Expert Comment

by:Bryan Butler
ID: 22687288
And another case would be:

( ### ) ### - ####

With spaces before/after the parens.  Do you need to handle this?
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

by Batuhan Cetin Regular expression is a language that we use to edit a string or retrieve sub-strings that meets specific rules from a text. A regular expression can be applied to a set of string variables. There are many RegEx engines for u…
Do you hate spam? I do, and I am willing to bet you do as well. I often wonder, though, "if people hate spam so much, why do they still post their email addresses on the web?" I'm not talking about a plain-text posting here. I am referring to the fa…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now