EmailAddressAtribute被忽略

Dar*_*bio 5 c# validation data-annotations

我有一个类定义的属性EmailAddress与属性EmailAddressAttribute来自System.ComponentModel.DataAnnotations

public class User : Entity
{
    [EmailAddress]
    public string EmailAddress { get; set; }

    [Required]
    public string Name { get; set; }
}

public class Entity
{
    public ICollection<ValidationResult> Validate()
    {
        ICollection<ValidationResult> results = new List<ValidationResult>();
        Validator.TryValidateObject(this, new ValidationContext(this), results);
        return results;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我将的值设置为EmailAddress无效的电子邮件(例如'test123')时,该Validate()方法会告诉我该实体有效。

RequiredAttribute验证工作(例如,设置Namenull节目我一个验证错误)。

我如何EmailAddressAttribute在验证器中工作?

Dar*_*bio 6

在使用了每个方法可用的重载之后,我发现了以下重载,其中包含一个名为validateAllProeprties.

当此设置为true对象时,将验证属性。

Validator.TryValidateObject(this, new ValidationContext(this), results, true);
Run Code Online (Sandbox Code Playgroud)

我不确定为什么您不想验证所有属性,但是将此设置为false或不设置(默认为false)只会验证所需的属性。

这篇MSDN 文章解释了。


fab*_*aby 1

Microsoft.Web.Mvc.DataAnnotations.dll要使用数据注释验证器进行验证,您应该添加对程序集和程序集的引用 System.ComponentModel.DataAnnotations.dll

那么您需要在 Global.asax 文件中注册 DataAnnotations Model Binder。将以下代码行添加到Application_Start()事件处理程序,使该Application_Start()方法如下所示:

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();
}
Run Code Online (Sandbox Code Playgroud)

之后,您将 注册dataAnnotationsModelBinder为整个 ASP.NET MVC 应用程序的默认模型绑定器

那么你的代码应该可以正常工作

public class User : Entity
{
    [EmailAddress]
    public string EmailAddress { get; set; }

    [Required]
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

请参阅此处的文档