You are on page 1of 11

ASP.

NET MVC Model Validation


using Data Annotations
In ASP.NET MVC, there are several ways to validate the model data prior to saving
the data into the data store.

1. Validate the model data explicitly

2. Specify Data Annotations [Recommended]

Data Annotation is recommended because there are built-in Data Annotations in .NET
Framework. You don’t have to implement your own validation logic, instead
specifying the Validation Data Annotation that you need. The Data Annotations
specified support both server-side & client-side validation. In case the built-in cannot
fulfill your requirements, you can also implement your own Data Annotation.

Built-in Data Annotations

Namespace: System.ComponentModel.DataAnnotations
Validation Attribute Description

CompareAttribute Compares two properties

CustomValidationAttribute Specifies a custom validation method

DataTypeAttribute Data type of the data field

MaxLengthAttribute Max. length of array or string data allowed

MinLengthAttribute Min. length of array or string data allowed

RangeAttribute Numeric range constraints for the data field value

RegularExpressionAttribute Data field value must match the specified regular expression

RequiredAttribute Data field value is required

StringLengthAttribute Min. and max. length of characters that are allowed in a data field

Namespace: System.Web.Security

Validation Attribute Description

Validates whether a password field meets the current password requirements for the
MembershipPasswordAttribute
membership provider
Code Sample

using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Security;

1 namespace AspNetMvc.Models
2 {
3 public class User
4 {
5 [DataType(DataType.Text)]
6 [StringLength(30, MinimumLength = 6)]
7 [Required()]
8 public string UserName { get; set; }
9
10 [DataType(DataType.Password)]
11 [StringLength(255, MinimumLength = 8)]
12 [Required()]
13 [MembershipPassword()]
14 public string Password { get; set; }
15
16 [Compare("Password")]
17 [DataType(DataType.Password)]
18 [StringLength(255, MinimumLength = 8)]
19 [Required()]
20 [MembershipPassword()]
21 public string ConfirmPassword { get; set; }
22
23 [DataType(DataType.EmailAddress)]
24 [StringLength(128)]
25 [Required()]
26 public string Email { get; set; }
27
28 [DataType(DataType.PhoneNumber)]
29 [RegularExpression("^[0-9]{8}$")]
30 [StringLength(32)]
31 public string Phone { get; set; }
32
33 [DataType(DataType.Date)]
34 public DateTime Birthday { get; set; }
35
[DataType(DataType.MultilineText)]
[StringLength(255)]
public string Remarks { get; set; }
}
}
Snapshot
On to the Preview
Let’s say you had the following “Customer” domain model (or view model, depending on
your project structure) in an MVC 6 project:

public class Customer


{
public string Email { get; set; }
public int Age { get; set; }
public string ProfilePictureLocation { get; set; }
}
When it comes time to create/edit this Customer, you will probably have a
CustomerController and a simple form that just uses one of the Html.EditorFor() methods
that the ASP.NET MVC tooling generates for you (or you can write yourself). It should
look something like this:
With no validation, the customer can enter nonsense for an email address, and then can
even report their age as a negative number! With the built-in Data Annotations
validation, I could do a bit better by adding a Range to the age, adding a
RegularExpression for email (yuck!), and adding some required attributes. However, I’d
still be able to report my age as 10.75 years old, and my profile picture could still be any
string. Let’s use Data Annotations along with this project, Data Annotations Extensions,
and see what we can get:

public class Customer


{
[Email]
[Required]
public string Email { get; set; }

[Integer]
[Min(1, ErrorMessage="Unless you are benjamin button you a
re lying.")]
[Required]
public int Age { get; set; }

[FileExtensions("png|jpg|jpeg|gif")]
public string ProfilePictureLocation { get; set; }
}
Now let’s try to put in some invalid values and see what happens:

Creating Your Model


In the Models folder, create a new User.cs file with a User class that you can use as a
model. To start with, I’ll use the following class:

public class User


{
public string Email { get; set; }
public string Password { get; set; }
public string PasswordConfirm { get; set; }
public string HomePage { get; set; }
public int Age { get; set; }
}
Next, create a simple controller with at least a Create method, and then a matching
Create view (note, you can do all of this via the MVC built-in tooling). Your files will look
something like this:
UserController.cs:

public class UserController : Controller


{
public ActionResult Create()
{
return View(new User());
}

[HttpPost]
public ActionResult Create(User user)
{
if (!ModelState.IsValid)
{
return View(user);
}

return Content("User valid!");


}
}
Create.cshtml:

@model NuGetValidationTester.Models.User

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusi
ve.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>

@Html.EditorForModel()

<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
In the Create.cshtml view, note that we are referencing jquery validation and jquery
unobtrusive (jquery is referenced in the layout page). These MVC 3 included scripts are
the only ones you need to enjoy both the basic Data Annotations validation as well as the
validation additions available in Data Annotations Extensions. These references are
added by default when you use the MVC 3 “Add View” dialog on a modification template
type.
Now when we go to /User/Create we should see a form for editing a User
Email address validation

use EmailAddress Attribute which resides
inside System.ComponentModel.DataAnnotations.
Your code should look similar to this:

[Display(Name = "Email address")]


[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }

using the [Range(min, max)]validator this far for checking values, like e.g.:
[Range(1, 10)]
public int SomeNumber { get; set; }
However - now I need to check the min and max condition separately. I
expected to find attributes like these:

[MinValue(1, "Value must be at least 1")]


[MaxValue(10, "Value can't be more than 10")]
public int SomeNumber { get; set; }

Extensions. The new and improved User.cs model class.

{
[Required]
[Email]
public string Email { get; set; }

[Required]
public string Password { get; set; }

[Required]
[EqualTo("Password")]
public string PasswordConfirm { get; set; }

[Url]
public string HomePage { get; set; }

[Integer]
[Min(1)]
public int Age { get; set; }
}
Now let’s re-run our form and try to use some invalid values:

You might also like