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>
Get Professional ASP.NET MVC 4 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.