Email validation using data annotation

Introduction


To validate an email address entered by a user in an ASP.NET MVC application, we use the EmailAddressAttribute .

Usage


[Required]
[Display(Name = "Email")]
[EmailAddress(ErrorMessage ="Invalid email address")]
public string Email { get; set; }

We associate the EmailAddressAttribute annotation to our email string. That way, if a user enter an invalid email address he will get the "Invalid email address" error message.

Namespace


To use the EmailAddressAttribute, you have to include this namespace:

using System.ComponentModel.DataAnnotations;