Client Side Validation for MVC 2 P2

MVC 2 Preview 1 added support for DataAnnotations. In my MSDN article How to: Validate Model Data Using DataAnnotations Attributes I covered the basics of validation. Preview 2 adds client validation with the addition of one line of code. The following class contains the model I use in my sample download.

 public class Pals {
       public float Height { get; set; }
       public string Name { get; set; }
       public int ID { get; set; }
       public bool cool { get; set; }
       public string email { get; set; }
       public string Bio { get; set; }

Only two minor additions are required to get client side validation. Add the jQuery and jQuery.Validate scripts for client download and call Html.ClientValidationEnabled before Html.BeginForm(). I like to use the CDN reference to jQuery and add it to my Views\Shared\Site.Master file. All my views can take advantage of client side validation without referencing the script files directly. Because it's a CDN, once the scripts are downloaded from any URL, they are in the local client cache.

The following snippet shows my additions to the Views\Shared\Site.Master file.

 <%--     Add CDN jQuery validation scripts--%>
<%--jQuery Debug  use jquery-1.3.2.min.js for Release --%>
<script src="" type="text/javascript"></script>
<%--jQuery Validation Debug; Use jquery.validate.min.js for release --%>
  <script src="" type="text/javascript"></script>
    <script src="<%= Url.Content("~/Scripts/MicrosoftMvcJqueryValidation.js") %>" type="text/javascript"></script>

My updated sample uses the new EditorForModel templated helper. The Edit markup is shown below.

 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<MvcSimpObj.Models.Pals>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

 <% Html.ClientValidationEnabled = true;   %> 
    <% using (Html.BeginForm()) { %>
            <%= Html.ValidationSummary("Broken stuff:") %>
            <%= Html.EditorForModel() %>
            <input type="submit" value="  Submit  " />
    <% } %>
  <% Html.RenderPartial("linksPalsID"); %>

The line  <% Html.ClientValidationEnabled = true; %>  just before the BeginForm enables client side validation.  Tabbing out of an input box instantly displays the validation error to the side of the control. You can use Fiddler or FireBug to verify the validation is client side.

The following image displays client side error messages. Notice the validation summary is empty, the validation summary occurs on the server side. You can correct the email alias ( for example) and it will instantly remove the validation error, even before you tab out of the input control.