Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Regular Expression Validator not validating as expected

Tags:

c#

regex

asp.net

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>
like image 335
Burning Hippo Avatar asked Dec 10 '25 23:12

Burning Hippo


2 Answers

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.

like image 50
Bobson Avatar answered Dec 12 '25 13:12

Bobson


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

like image 38
Win Avatar answered Dec 12 '25 13:12

Win