Monday, May 3, 2010

MVC 2 Client Side Model Validation with ExtJS

One of the most exciting new features in MVC 2 is "Enhanced Model Validation support across both server and client". The new enhanced support allows for client side validation to be dynamically generated into a view quickly and easily using DataAnnotations attributes on models. This means that by simply dressing up your model properties with attributes, your web pages can instantly have dynamic client side validation; all generated and maintained for you by the MVC framework!

MVC 2 enhanced model validation really is a terrific new feature...so, what's the problem? Microsoft uses JQuery, we use ExtJS.

We here at CodeSmith absolutely love MVC, but many of features are designed to use JQuery, and we (for several different reasons) prefer to use the ExtJS Framework. This means that (as it stands) to use both we must reference both, and no one wants to download two complete AJAX frameworks just to view one webpage.

Good news, we fixed that!

Introducing: Ext.ux.MvcFormValidator

The MVC client side form validator dynamically generates a small blob of configuration for each form, and stores them in window.mvcClientValidationMetadata. Once the page loads up, the client side validator framework loads all these configs, and then starts monitoring the specified forms for validation.

What we have done is created an alternative form validation context (modeled after Sys.Mvc.FormContext) that loads the validation configuration, and requires no changes in the MVC generated code, but uses ExtJS as it's back end. This means that the only thing you have to do is reference Ext.ux.MvcFormValidator.js, and it will enable you to use the ExtJS Core for form validation instead of having to import MicrosoftMvcValidation and the other Microsoft AJAX libraries.

Features

  • Requires only the ExtJS Core.
  • Implements all four default validators: Required, Range, StringLength, RegularExpression
  • Supports integration of custom validators with almost no code change.
    • Just update Sys.Mvc.ValidatorRegistry.validators to call Ext.Mvc.ValidatorRegistry.validators
  • Displays field messages as well as summary.
  • Extends Ext.util.Observable and uses events.
  • Lightweight; less than 300 lines of code.

Downloads

Ext.ux.MvcFormValidator.js: http://codesmith.googlecode.com/files/Ext.ux.MvcFormValidator.js
Demo Solution: http://codesmith.googlecode.com/files/ExtUxMvcFormValidationDemo.zip

Example

Model

public class ValidationDemoModel
{
    [Required]
    [StringLength(10)]
    public string Name { get; set; }

    [Range(10000, 99999)]
    public string ZipCode { get; set; }

    [RegularExpression (@"\d{3}[-]?\d{3}[-]?\d{4}", ErrorMessage="The field Phone must be valid phone number.")]
    public string Phone { get; set; }

    [AcceptBox]
    public bool Accept { get; set; }

Site.Master

<script src="/Scripts/ext-core.js" type="text/javascript"></script>
<script src="/Scripts/Ext.ux.MvcFormValidator.js" type="text/javascript"></script>
<script src="/Scripts/CustomValidators.js" type="text/javascript"></script>

View

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Validation Demo</h2>
        <% Html.EnableClientValidation(); %>
        <% using (Html.BeginForm()) { %>
        <%= Html.LabelFor(m => m.Name) %>:
        <%= Html.TextBoxFor(m => m.Name)%>
        <%= Html.ValidationMessageFor(m => m.Name)%>
        <br />
        <%= Html.LabelFor(m => m.Phone) %>:
        <%= Html.TextBoxFor(m => m.Phone)%>
        <%= Html.ValidationMessageFor(m => m.Phone)%>
        <br />
        <%= Html.LabelFor(m => m.ZipCode) %>:
        <%= Html.TextBoxFor(m => m.ZipCode)%>
        <%= Html.ValidationMessageFor(m => m.ZipCode)%>
        <br />
        <%= Html.LabelFor(m => m.Accept) %>:
        <%= Html.CheckBoxFor(m => m.Accept)%>
        <%= Html.ValidationMessageFor(m => m.Accept)%>
        <br />
        <input type="submit" value="Submit" />
        <%  } %>
</asp:Content>

Controller Action

[HttpGet]
public ActionResult ValidationDemo()
{
    var model = new ValidationDemoModel();
    return View(model);
}

Custom Validator

Ext.Mvc.ValidatorRegistry.validators["acceptbox"] = function (rule) {
    return function (value, context) {
        return context.fieldContext.elements[0].checked === true;
    };
};

No comments:

Post a Comment

Real Time Web Analytics