ASP.NET email validator regex

前端 未结 6 1122
走了就别回头了
走了就别回头了 2020-12-02 22:24

Does anyone know what the regex used by the email validator in ASP.NET is?

相关标签:
6条回答
  • 2020-12-02 22:56

    E-mail addresses are very difficult to verify correctly with a mere regex. Here is a pretty scary regex that supposedly implements RFC822, chapter 6, the specification of valid e-mail addresses.

    Not really an answer, but maybe related to what you're trying to accomplish.

    0 讨论(0)
  • 2020-12-02 22:59

    We can use RegularExpressionValidator to validate email address format. You need to specify the regular expression in ValidationExpression property of RegularExpressionValidator. So it will look like

     <asp:RegularExpressionValidator ID="validateEmail"    
      runat="server" ErrorMessage="Invalid email."
      ControlToValidate="txtEmail" 
      ValidationExpression="^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" />
    

    Also in event handler of button or link you need to check !Page.IsValid. Check sample code here : sample code

    Also if you don't want to use RegularExpressionValidator you can write simple validate method and in that method usinf RegEx class of System.Text.RegularExpressions namespace.

    Check example:

    example

    0 讨论(0)
  • 2020-12-02 23:09

    For regex, I first look at this web site: RegExLib.com

    0 讨论(0)
  • 2020-12-02 23:13

    I don't validate email address format anymore (Ok I check to make sure there is an at sign and a period after that). The reason for this is what says the correctly formatted address is even their email? You should be sending them an email and asking them to click a link or verify a code. This is the only real way to validate an email address is valid and that a person is actually able to recieve email.

    0 讨论(0)
  • 2020-12-02 23:14

    Apart from the client side validation with a Validator, I also recommend doing server side validation as well.

    bool isValidEmail(string input)
    {
        try
        {
            var email = new System.Net.Mail.MailAddress(input);
            return true;
        }
        catch
        {
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-02 23:18

    Here is the regex for the Internet Email Address using the RegularExpressionValidator in .NET

    \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
    

    By the way if you put a RegularExpressionValidator on the page and go to the design view there is a ValidationExpression field that you can use to choose from a list of expressions provided by .NET. Once you choose the expression you want there is a Validation expression: textbox that holds the regex used for the validator

    0 讨论(0)
提交回复
热议问题