Email model validation with DataAnnotations and DataType

Solution 1:

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.

Solution 2:

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

Solution 3:

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;
}