Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc [DataType(DataType.EmailAddress) no validation

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?

like image 776
GibboK Avatar asked Jul 12 '12 14:07

GibboK


People also ask

What are the types of validation in MVC?

The following three type of validations we can do in ASP.NET MVC web applications: HTML validation / JavaScript validation. ASP.NET MVC Model validation.

Can we do validation in MVC using data annotations?

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.

Which attribute is used for validation in MVC?

ASP.NET MVC provides a unique feature in which we can validate the models using the Data Annotation attribute.

Is data annotation server side validation in MVC?

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.


2 Answers

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!

like image 61
SarahK Avatar answered Sep 17 '22 18:09

SarahK


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; } 
like image 20
GibboK Avatar answered Sep 17 '22 18:09

GibboK