EmailAddressAttribute如何工作?

时间:2013-11-21 23:58:03

标签: validation asp.net-mvc-5

我使用ASP.NET MVC 5并需要对电子邮件进行验证。

我有以下视图模型:

public class RegisterViewModel
{
    [Required]
    [Display(Name = "User name")]
    [EmailAddress(ErrorMessage = "The email address is not valid")]
    public string UserName { get; set; }

和页面:

@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>

“必需”的验证工作,但我可以输入“bla-bla-bla”到UserName文本字段,验证器“email”不起作用。服务器端的问题相同,Model.IsValid = true。为什么以及如何解决?

2 个答案:

答案 0 :(得分:4)

派对晚了几年,但我猜有些人还在寻找这个。如果您使用System.ComponentModel.DataAnnotations中的那个,那么这就是代码。参考:http://referencesource.microsoft.com/#System.ComponentModel.DataAnnotations/DataAnnotations/EmailAddressAttribute.cs

正如你所看到的,那里有一个疯狂的RegEx。

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);
    }

答案 1 :(得分:-1)

它验证具有有效电子邮件格式的电子邮件地址是作为属性值提供的。它基本上只是确保它具有正确的格式...例如stink@dink.com

如果您希望它验证电子邮件是真实的......那就不是。