Wednesday, 9 December 2009

Validating input for an email address

Use this pretty, simple, and pretty simple regular expression validator:
<asp:RegularExpressionValidator ID="valEmailAddress" ControlToValidate="EmailTextBox" ValidationExpression=".*@.*\..*" ErrorMessage="Email address is invalid" EnableClientScript="true" runat="server" ValidationGroup="Insert">*</asp:RegularExpressionValidator>

Or, if you want to do it in code rather than use a control, try this:

public static bool isEmail(string inputEmail)
    if( inputEmail == null || inputEmail.Length == 0 )
        throw new ArgumentNullException( "inputEmail" );

    const string expression = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                              @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +

    Regex regex = new Regex(expression);
    return regex.IsMatch(inputEmail);

No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!