Client-side validation with jQuery

We're already running quite a tight ship with our form, but it's a little frustrating to receive the error messages only after we submit the form. Think about thousands of people constantly submitting incorrect data to your site. It's an unnecessary use of your valuable resources. Client-side validation goes some way to prevent this, but used to be a real bind to implement; with ASP.NET MVC though, it's remarkably easy.

Getting ready

Up until about ASP.NET MVC 2 RC, there were two options for implementing client-side validation—Microsoft Ajax and jQuery. Of the two, the jQuery option was mysteriously absent from the final release. It will be the jQuery option that we will focus on in this recipe. Beyond the jQuery files already contained within any new ASP.NET MVC 2 project, this recipe has a requirement for the somewhat elusive jQuery connector. I've given up trying to track down the file's permanent residence, so will simply say that it is included within the book's source code, and can be tracked down (with some effort) on Google by searching for MicrosoftMvcJQueryValidation.js. You can also download an amended version from http://blog.dogma.co.uk.

How to do it...

  1. Starting from the previous recipe, let's add a call to Html.EnableClientValidation() above our form in Views/Home/Index.aspx.
    Views/Home/Index.aspx:
    <% Html.EnableClientValidation(); %>
    <% using (Html.BeginForm()) {%>
    
  2. Open up your Site.Master file and add the following three lines above the closing body tag, assuming that you added the connector file to the root of your Scripts folder.
    Views/Shared/Site.Master:
    <script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
    <script src="/Scripts/MicrosoftMvcJQueryValidation.js" type="text/javascript"></script>
    
    How to do it...client-side validation, jQuery usedstarting with
  3. Build and run your project, then submit your form. Unless you've filled in all the required fields, you wouldn't be able to make a submission. jQuery, with the help of our connector (MicrosoftMvcJQueryValidation.js), has prevented the POST. What's more, if you start correcting the mistakes, the error messages will disappear without having to attempt resubmission.

How it works...

In the first step, we added a call to an HTML helper called EnableClientValidation. The EnableClientValidation method should be added just above the targeted form and it basically tells the form to render some extra information. The extra information is a JSON (JavaScript Object Notation) map containing all the validation conditions for the form within a script block. The script block is placed directly beneath the form and attaches the map to a window object called mvcClientValidationMetadata. Have a look at the HTML source of your form for a complete example.

Home/Index (View Source):
if (!window.mvcClientValidationMetadata) {
window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.push({ "Fields": [{
"FieldName": "FirstName", "ReplaceValidationMessageContents": true, "ValidationMessageId": "FirstName_validationMessage", "ValidationRules": [{
"ErrorMessage": "The field First Name must be a string with a maximum length of 50.", "ValidationParameters": { "minimumLength": 0, "maximumLength": 50 },
"ValidationType": "stringLength"
}]
},
...

The validation itself is handled by a very robust jQuery plug-in called jQuery Validation. At this point though, the validation plug-in needs to be initiated and, as the mvcClientValidationMetdata object is a Microsoft invention that means nothing to jQuery, we need a bridge. Enter MicrosoftMvcJQueryValidation.js (the connector). This file consumes the JSON map and reformats it as an options object that the validation plug-in can understand. The connector then calls the validation plug-in into action.

So far, we have mirrored validation on the client and server with a small amount of effort. What else can we do?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset