EmailAddressAtribute ignored

I have a class that defines a property EmailAddresswith an attribute EmailAddressAttributefrom 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;
    }
}

When I set the value EmailAddressas an invalid email (for example, "test123"), the method Validate()tells me that the object is valid.

Validation works RequiredAttribute(for example, setting Nameto nullshows me a validation error).

How do I get EmailAddressAttributein my validator?

+4
source share
2 answers

To use validation using data annotation validators, you must add both references to Microsoft.Web.Mvc.DataAnnotations.dlland assembly System.ComponentModel.DataAnnotations.dll.

DataNunotations Global.asax. Application_Start(), Application_Start() :

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

dataAnnotationsModelBinder ASP.NET MVC

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

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

+1

, , , validateAllProeprties.

true, .

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

, , false ( - false), .

MSDN .

+1

Source: https://habr.com/ru/post/1548648/


All Articles