Client Validation

Client validation for data annotation attributes is on by default with the MVC framework. As an example, look at the Title and Price properties of the Album class:

[Required(ErrorMessage = "An Album Title is required")]
public string   Title      { get; set; }

[Required(ErrorMessage = "Price is required")]
[Range(0.01, 100.00,
    ErrorMessage = "Price must be between 0.01 and 100.00")]
public decimal Price       { get; set; }

The data annotations make these properties required, and also put in some restrictions on the length and the range of the values the properties hold. The model binder in ASP.NET MVC performs server-side validation against these properties when it sets their values. These built-in attributes also trigger client-side validation. Client-side validation relies on the jQuery validation plugin.

jQuery Validation

As mentioned earlier, the jQuery validation plugin (jquery.validate) exists in the Scripts folder of a new MVC 3 application by default. If you want client-side validation, you'll need to have a couple script tags in place. If you look in the Edit or Create views in the StoreManager folder, you'll find the following lines inside:

<script src="@Url.Content("∼/Scripts/jquery.validate.min.js")" 
<script src="@Url.Content("∼/Scripts/jquery.validate.unobtrusive.min.js")"

AJAX Settings in web.config

By default, unobtrusive JavaScript and client-side validation are enabled ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.