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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With