共用方式為


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 {
       [Required()]
       [Range(33,99)]
       public float Height { get; set; }
       [Required()]
       [StringLength(7)]
       public string Name { get; set; }
       [ScaffoldColumn(false)]
       public int ID { get; set; }
       public bool cool { get; set; }
       [DataType(DataType.EmailAddress)]
       [RegularExpression(@"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$")]
       public string email { get; set; }
       [DataType(DataType.MultilineText)]
       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="https://ajax.microsoft.com/ajax/jQuery/jquery-1.3.2.js" type="text/javascript"></script>
<%--jQuery Validation Debug; Use jquery.validate.min.js for release --%>
  <script src="https://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.js" 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">

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

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 (a@bb.com for example) and it will instantly remove the validation error, even before you tab out of the input control.

ClientValMVC.zip

Comments

  • Anonymous
    October 13, 2012
    Good Article Rick.