2

I am doing validation for 10 digit North American phone numbers (coding below). I am accepting digits only. What I can't seem to figure out is how to alter this so that if the number entered begins with 911, 411 or a 0, an error is thrown.

string phoneNum = phoneTextBox.Text;
Regex regex = new Regex(@"^\d{10}$");
Match match = regex.Match(phoneNum);
if (!match.Success)
{
   MessageBox.Show(phoneNum + " is not a valid 10 digit phone number (Ex. 6134561234)");
}
Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
PrgmRNoob
  • 151
  • 1
  • 5
  • 18
  • 3
    You should use another regex for that validation. check here - http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation – realnero Mar 25 '13 at 15:34

3 Answers3

2

Try this:

Regex regex = new Regex(@"^(?!411|911|0)\d{10}$");
                           +++++++++++++

They're called negative lookahead assertions.

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
1

You can use more advance patterns. Try to find the one here - http://regexlib.com/DisplayPatterns.aspx?cattabindex=6&categoryId=7

I've tried running Regex Tracer and it finds ok number 4111111111 for patter - ^\d{10}$.

realnero
  • 994
  • 6
  • 12
-1

Another alternative - a phone number parser: http://www.codeproject.com/Articles/31998/Advanced-Phone-Number-Type-Implementation

Tony
  • 602
  • 1
  • 7
  • 10