简体   繁体   English

使用不显眼的 javascript / MVC3 和 DataAnnotations 验证电子邮件地址

[英]Validating an e-mail address with unobtrusive javascript / MVC3 and DataAnnotations

jQuery Validation makes it simple to validate an email address: jQuery 验证使验证 email 地址变得简单:

$("someForm").validate({
    rules: {
        SomeField: {
            required: true,
            email: true,
            remote: {
                type: "POST",
                url: "CheckEmail"
            }
        }
    }
});

This makes it so that SomeField is required, must be formatted as an e-mail address and also performs a remote call to the CheckEmail action (check for duplicates).这使得 SomeField 是必需的,必须格式化为电子邮件地址,并且还执行对 CheckEmail 操作的远程调用(检查重复项)。

I like to make things as simple as possible so I can do a lot of the same stuff with Data Annotations:我喜欢让事情尽可能简单,这样我就可以用数据注释做很多同样的事情:

public class RegisterModel {
    [Required]
    [Remote("CheckEmail", "Home", HttpMethod="POST")]
    public string SomeField { get; set; }
}

Does ASP.net MVC 3 / Data Annotations have a built-in/simple way to validate to make sure the e-mail address is in the correct format? ASP.net MVC 3 / 数据注释是否具有内置/简单的验证方法以确保电子邮件地址的格式正确?

I would like it to produce unobtrusive javascript if possible.如果可能的话,我希望它产生不引人注目的 javascript。

I think this is the code you are looking for (this is similar to ScottGu's example but also shows the DisplayName in the default error message instead of the property name):我认为这是您要查找的代码(这类似于 ScottGu 的示例,但也在默认错误消息中显示 DisplayName 而不是属性名称):

public class EmailAttribute : RegularExpressionAttribute
{
    private const string defaultErrorMessage = "'{0}' must be a valid email address";

    public EmailAttribute() : 
        base("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$")
    { }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(defaultErrorMessage, name);
    }

    protected override ValidationResult IsValid(object value,
                                            ValidationContext validationContext)
    {
        if (value != null)
        {
            if (!base.IsValid(value))
            {
                return new ValidationResult(
                    FormatErrorMessage(validationContext.DisplayName));
            }
        }

        return ValidationResult.Success;
    }
}

Then your model property would look like this:然后您的 model 属性将如下所示:

    [DisplayName("My Email Address")]
    [Email]
    public string EmailAddress { get; set; }

Does ASP.net MVC 3 / Data Annotations have a built-in/simple way to validate to make sure the e-mail address is in the correct format? ASP.net MVC 3 / 数据注释是否具有内置/简单的验证方法以确保电子邮件地址的格式正确?

Not built-in but you could use a [RegularExpression] .不是内置的,但您可以使用[RegularExpression] Scott Gu illustrated an example of such regex in a blog post . Scott Gu 在一篇文中举例说明了这种正则表达式。 He wrote a custom EmailAttribute deriving from RegularExpressionAttribute to avoid repeating logic.他编写了一个从RegularExpressionAttribute派生的自定义EmailAttribute以避免重复逻辑。

The Data Annotation Extensions library has an [Email] attribute that allows for validating an email address.数据注释扩展库有一个[Email]属性,允许验证 email 地址。

There is also a blog post outlining how to use the library.还有一篇博客文章概述了如何使用该库。

EmailAddress attribute is built into framework already, no need for Data Annotation Extensions or other logic: Email model validation with DataAnnotations and DataType EmailAddress 属性已经内置到框架中,不需要数据注释扩展或其他逻辑: Email model 验证与 DataAnnotations 和 DataType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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