Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email model validation with DataAnnotations and DataType

I have following model:

public class FormularModel
{
    [Required]
    public string Position { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Required]
    public string Webcode { get; set; }
}

Required validation works fine. But when i try with DataType it doesn't react.

Here is my razor code for the email control:

   @Html.TextBoxFor
          (model => model.Email, 
           new { @style = "width: 175px;", @class = "txtField" }
          ) * 

So, anyone know an answer?

TIA

like image 616
lifeofbenschi Avatar asked Jan 24 '12 15:01

lifeofbenschi


People also ask

Can we do validation in MVC using data annotations?

In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.

What are different attributes available in model for validation?

See [Required] attribute for details about this attribute's behavior. [StringLength]: Validates that a string property value doesn't exceed a specified length limit. [Url]: Validates that the property has a URL format. [Remote]: Validates input on the client by calling an action method on the server.


4 Answers

DataType attribute is used for formatting purposes, not for validation.

I suggest you use ASP.NET MVC 3 Futures for email validation.

Sample code:

[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }

If you happen to be using .NET Framework 4.5, there's now a built in EmailAddressAttribute that lives in System.ComponentModel.DataAnnotations.EmailAddressAttribute.

like image 180
Leniel Maccaferri Avatar answered Oct 11 '22 12:10

Leniel Maccaferri


The DataAnnotationsExtensions project has an Email attribute that you can use.

like image 42
jrummell Avatar answered Oct 11 '22 12:10

jrummell


I have looked at the source code (reverse engineered by Reflector) and DataType variants are actually not even implemented! (This was for DateType.Date)

So it is not going to work.

I would personally use RegexValidation for email.


For clarity, here is the implementation of IsValid in class DataTypeAttribute:

public override bool IsValid(object value)
{
    return true;
}
like image 3
Aliostad Avatar answered Oct 11 '22 11:10

Aliostad


I used this regex pattern which will allow some of the newer longer extensions (.mynewsite, etc).

@"^[\w-_]+(\.[\w!#$%'*+\/=?\^`{|}]+)*@((([\-\w]+\.)+[a-zA-Z]{2,20})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$"

Not Valid, among others too:

Examples that work:

like image 2
RichieMN Avatar answered Oct 11 '22 12:10

RichieMN