1

I'm trying to validate a phone number against a RegEx.

I was provided with this answer:

Regular Expression for Phone Number

which defines the expression to validate the following phone number: +44 (0) 1234 123456

I've ported it from JS to C#, to be

var regexPhone = new Regex(@"^(?!([^-]*-){5})(\+\d+)?\s*(\(\d+\))?[- \d]+$");

This works, but the validator is also applied to phone number fields that are allowed to be blank, e.g. a Fax (not everyone has one of those old-fangled devices anymore).

How can I change this to allow blanks, as well as to validate against the number above?

edit: the answer below works for the number above but it's failing for this: + 44 (0)20 1234 1234. Is there something else I can add for this?

Community
  • 1
  • 1
DaveDev
  • 41,155
  • 72
  • 223
  • 385

2 Answers2

5

Simply add a |^$ at the end:

var regexPhone = new Regex(@"^(?!([^-]*-){5})(\+\d+)?\s*(\(\d+\))?[- \d]+$|^$");

edit: Since you want a more relaxed regex, whitespace-wise, just sprinkle in \s*:

var regexPhone = new Regex(@"^\s*(?!([^-]*-){5})(\+\s*\d+)?\s*(\(\s*\d+\s*\))?\s*[- \d]+\s*$|^\s*$");
Blindy
  • 65,249
  • 10
  • 91
  • 131
  • this works, for the number above but it's failing for this: `+ 44 (0)20 1234 1234`. Is there something else I can add for this? Question updated to reflect. – DaveDev Feb 17 '11 at 14:09
0

I've tried it and it works.

 <asp:TextBox runat="server" ID="testInput"></asp:TextBox>
            <asp:RegularExpressionValidator ValidationExpression="aa|^$" 
runat="server" ControlToValidate="testInput"></asp:RegularExpressionValidator>
Danil
  • 1,883
  • 1
  • 21
  • 22