O'Reilly logo

Professional ASP.NET MVC 4 by Scott Hanselman, K. Scott Allen, Brad Wilson, Phil Haack, Jon Galloway

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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")]
[StringLength(160)]
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 4 application by default. If you want client-side validation, you'll need to have a couple of 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="∼/Scripts/jquery.validate.min.js")
></script>
<script src="∼/Scripts/jquery.validate.unobtrusive.min.js")
   ></script>
Ajax Settings in web.config
By default, unobtrusive JavaScript and client-side validation are enabled in an ASP.NET MVC application. However, you can change the behavior ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required