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>
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With