MVC / Validating an email address with DataAnnotation

If you’re using MVC and want to capture an email address, there is a great built-in way to validate the address. When creating your model, add the [EmailAddress] DataAnnotation like below.

 [Required]
 [EmailAddress]
 [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
 [DataType(DataType.EmailAddress)]
 [Display(Name = "Email Address")]
 public string Email { get; set; }

Then you can add to your view:

 <li>
 <%: Html.LabelFor(m => m.Email) %>
 <%: Html.TextBoxFor(m => m.Email) %>
 </li>

And if you enter an invalid email you’ll get the error:

Invalid Email Address

MVC / Validating an email address with DataAnnotation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s