Welcome to the CodeSmith Community!

MVC 2 Client Side Model Validation with ExtJS

CodeSmith Community

A description has not yet been added to this group.

MVC 2 Client Side Model Validation with ExtJS

Rate This
  • Comments 6

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;
    };
};

kick it on DotNetKicks.com

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • * Please enter your name
  • * Please enter a comment
  • Post
  • You've been kicked (a good thing) - Trackback from DotNetKicks.com

  • Hello. I'm try to run your demo solution and have javascript error at start.

  • Hello,

    What error are you getting? What version of Ext are you using?

    Thanks

    -Blake Niemyjski

  • Hello. You using mvc HTML helpers in sample for UI. How can use with UI Ext.JS. For example:

    ReplaceFixGroup = Ext.extend(FormPanel, {

    title: 'form',

      initComponent: function() {

    var oldFG = new Ext.form.ComboBox(

           Ext.apply(cbFixGroupConf, {

               id: 'oldFG'

               ,hiddenName:'oldFG_id'

               ,fieldLabel: 'oldfg'

               ,store: dsFixGroup // store getting items from server

           }));

    var newFG = new Ext.form.ComboBox(

           Ext.apply(cbFixGroupConf, {

               id: 'newFG'

               ,hiddenName:'newFG_id'

               ,fieldLabel: 'newfg'

               ,store: dsFixGroup

           }));

    var formConf = {

    api: { submit: Admin.ReplaceFixGroup_Submit }

    ,buttons: [ bReload, bSubmit ]

    ,items: [ oldFG, newFG ]

    }

    Ext.apply(this, Ext.apply(this.initialConfig, formConf));

    ReplaceFixGroup.superclass.initComponent.call(this);

    }

    });

  • Anton,

    This would not be applicable if you were building your forms with ExtJS because you could just use their built in validators.

    This is useful for people who are using MVC2 and don't want to make their end users download the JQuery and ExtJS frameworks on the same page.

    Tom

  • Sometimes I think that people don't realize how much code CodeSmith Tools has open sourced over the

Page 1 of 1 (6 items)
Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • * Please enter your name
  • * Please enter a comment
  • Post