How does EmailAddressAttribute work?

asp.net-mvc-5, validation

Solution

A few years late to the party, but I guess some people still look for this. If you are using the one from `System.ComponentModel.DataAnnotations` then this is the code for that. Reference: http://referencesource.microsoft.com/#System.ComponentModel.DataAnnotations/DataAnnotations/EmailAddressAttribute.cs

As you can see, there's an insane RegEx involved.

public override bool IsValid(object value) {
        if (value == null) {
            return true;
        }

        string valueAsString = value as string;

        // Use RegEx implementation if it has been created, otherwise use a non RegEx version.
        if (_regex != null) { 
            return valueAsString != null && _regex.Match(valueAsString).Length > 0;
        }
        else {
            int atCount = 0;

            foreach (char c in valueAsString) {
                if (c == '@') {
                    atCount++;
                }
            }

            return (valueAsString != null
            && atCount == 1
            && valueAsString[0] != '@'
            && valueAsString[valueAsString.Length - 1] != '@');
        }
    }

    private static Regex CreateRegEx() {
        // We only need to create the RegEx if this switch is enabled.
        if (AppSettings.DisableRegEx) {
            return null;
        }

        const string pattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
        const RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;

        // Set explicit regex match timeout, sufficient enough for email parsing
        // Unless the global REGEX_DEFAULT_MATCH_TIMEOUT is already set
        TimeSpan matchTimeout = TimeSpan.FromSeconds(2);

        try {
            if (AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT") == null) {
                return new Regex(pattern, options, matchTimeout);
            }
        }
        catch {
            // Fallback on error
        }

        // Legacy fallback (without explicit match timeout)
        return new Regex(pattern, options);
    }

Problem

I use ASP.NET MVC 5 and need to do validation for email. I have the following view model: ``` public class RegisterViewModel { [Required] [Display(Name = "User name")] [EmailAddress(ErrorMessage = "The email address is not valid")] public string UserName { get; set; } ``` and page: ``` @using (Html.BeginForm("AddUser", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() <h4>Create a new account.</h4> <hr /> @Html.ValidationSummary(true) <div class="form-group"> @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.UserName) </div> </div> ``` validator for "required" works, but I can enter "bla-bla-bla" to UserName text field and validator "email" does not work. The same problem on server side, Model.IsValid=true. Why and how to fix?

Original source