编程语言
首页 > 编程语言> > c# – EmailAddressAtribute被忽略

c# – EmailAddressAtribute被忽略

作者:互联网

我有一个类,它使用System.ComponentModel.DataAnnotations中的属性EmailAddressAttribute定义属性EmailAddress:

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

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

RequiredAttribute验证正在运行(例如,将Name设置为null会显示验证错误).

如何在验证器中使用EmailAddressAttribute?

解决方法:

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

当此属性设置为true时,对象将通过属性验证.

Validator.TryValidateObject(this, new ValidationContext(this), results, true);

我不确定为什么你不想验证所有属性,但将此设置为false或未设置(默认为false)将仅验证所需的属性.

MSDN article解释.

标签:c,data-annotations,validation
来源: https://codeday.me/bug/20190628/1321070.html