简体   繁体   中英

ASP.NET Regular Expression Validator not validating as expected

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM