Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmailAddressAtribute ignored

I have a class which defines the property EmailAddress with the attribute EmailAddressAttribute from 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 of EmailAddress to be an invalid email (e.g. 'test123'), the Validate() method tells me the entity is valid.

The RequiredAttribute validation is working (e.g. setting Name to null shows me a validation error).

How do I get EmailAddressAttribute working in my validator?

like image 724
Darbio Avatar asked Jul 16 '14 14:07

Darbio


2 Answers

After playing with the overloads available for each method, I found the following overload which includes a parameter called validateAllProeprties.

When this is set to true the object is property validated.

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

I'm not sure why you wouldn't want to validate all properties, but having this set to false or not set (defaults to false) will only validate required attributes.

This MSDN article explains.

like image 109
Darbio Avatar answered Oct 04 '22 22:10

Darbio


to use Validation with the Data Annotation Validators you should add both references to Microsoft.Web.Mvc.DataAnnotations.dll assembly and the System.ComponentModel.DataAnnotations.dll assembly.

then you need to register the DataAnnotations Model Binder in the Global.asax file. Add the following line of code to the Application_Start() event handler so that the Application_Start() method looks like this:

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

after that you have registered the dataAnnotationsModelBinder as the default model binder for the entire ASP.NET MVC application

then your code should work properly

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

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

refer here for documentation

like image 35
faby Avatar answered Oct 04 '22 23:10

faby