I'm using this code on an email field:
[Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email address")] public string Email { get; set; }
[DataType(DataType.EmailAddress)]
does not work (validation does not occur no at a server not on the client side).
I am not sure if I should implement myself a Custom Attribute or I can use one included with MVC 3.
Could you please suggest me a solution for creating a custom attribute in case I need to.
I read also about some additional extensions, example http://nuget.org/packages/DataAnnotationsExtensions.MVC3
Would you suggest it to me?
The following three type of validations we can do in ASP.NET MVC web applications: HTML validation / JavaScript validation. ASP.NET MVC Model validation.
In ASP.NET MVC, Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes.
ASP.NET MVC provides a unique feature in which we can validate the models using the Data Annotation attribute.
In ASP.NET MVC application we can do the Server Side Validation on the Model using Data Annotations. Data Annotations is a namespace that provides attribute classes, and these classes define metadata for controls. In MVC we decorate Model Properties with these attribute classes to provide metadata.
You could use the usual DataAnnotations library by just using [EmailAddress]
using System.ComponentModel.DataAnnotations; [Required] [EmailAddress] public String Email { get; set; }
Also just for reference, here's the regular expression version of this validation:
[RegularExpression(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")] public String Email {get; set;}
Best of luck!
At the moment I have solved my problem using DataAnnotationsExtensions
it just works, you add their library with NuGet
using DataAnnotationsExtensions; [Required] [DataType(DataType.EmailAddress)] [Email] public string Email { get; set; }
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