3

I am trying to validate a phone number in the format (###)###-#### with \([0-9]{3}\)[0-9]{3}-[0-9]{4} in visual studio using the regular expression validator. I am receiving the error message with (111)111-1111. Yet when I do this on a regex testing site it works fine. Is there something else at play here that I am missing?

<asp:RegularExpressionValidator
     ID="PhoneValidator"
     runat="server"
     ErrorMessage="Phone Format Must Be (###)###-####" 
     ValidationExpression="/\([0-9]{3}\)[0-9]{3}-[0-9]{4}/g"
     Display="None" 
     ControlToValidate="PhoneTextBox">
</asp:RegularExpressionValidator>
2
  • 1
    Which site? Different regex engines have subtle differences. Commented Oct 21, 2013 at 18:58
  • I also notice that in your validator, you are using /pattern/g, which appears to be interpreted as part of the pattern instead of as a regex directive. Commented Oct 21, 2013 at 19:01

3 Answers 3

5

If you look at the example here, you'll see that in this context the regular expression should not start and end with / markers. Try this instead:

ValidationExpression="^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$"

The ^ and $ ensure you're not accepting extra characters before or after the phone number.

Sign up to request clarification or add additional context in comments.

Comments

1

You also want to consider extension too. For example, (770)123-4567 x1234.

((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}( x\d{0,})?

Validating Phone Numbers with Extensions in ASP.NET

Comments

0

I was actually having a problem elsewhere on the page sending a blank textbox of a date. Apparently C# interpreted the empty field as 01/01/0001 and therefore made it out of range. This was throwing everything else off. @neontapir You are right; I should not have had those on the expression. I didn't originally but just so happens I did when I posted this. Thanks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.