On All Things Web

Mar 29

 Not only does MVC support server-side validation, client-side validation is a possibility too.  Below is a sample form that sets up validation using client-side javascript.  These client-side features are made available from the MicrosoftMvcValidation.js file.  Take a look at the sample form with validation below.


<% Html.EnableClientValidation(); %>

<% Html.BeginForm(); %>


<%= Html.ValidationSummary(“The following errors have happened:”) %>


<fieldset>
 <legend>Form Values</legend>
 
 <div>
  First: <%= Html.TextBoxFor(i => i.FirstName) %>
  <%= Html.ValidationMessageFor(i => i.FirstName, “*”) %>
 </div>
 <div>
  Last: <%= Html.TextBoxFor(i => i.LastName) %>
  <%= Html.ValidationMessageFor(i => i.LastName, “*”)%>
 </div>
 <div>
  Email: <%= Html.TextBoxFor(i => i.Email) %>
  <%= Html.ValidationMessageFor(i => i.Email, “*”)%>
 </div>
 
 <input type=”submit” value=”Save” />
</fieldset>   


<% Html.EndForm(); %>


Client-side validation begins with a method call to enable client-side validation.  Under the scenes, this enables some of the built-in features, plus ensures some of the requirements within the UI happen (for instance, it ensures that each form has a unique ID).  If you compare this example with my server-side validation blog entry, you will see the form is the same; all that’s different is the call to this new client-side method.  Adding this method adds some new client-side code that sets up the components to do the validation.  This code looks like the following:


 if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.push({“Fields”:[{“FieldName”:”FirstName”,”ReplaceValidationMessageContents”:false,”ValidationMessageId”:”FirstName_validationMessage”,”ValidationRules”:[{"ErrorMessage":"First name required.","ValidationParameters":{},"ValidationType":"required"}]},{“FieldName”:”LastName”,”ReplaceValidationMessageContents”:false,”ValidationMessageId”:”LastName_validationMessage”,”ValidationRules”:[{"ErrorMessage":"Last name required.","ValidationParameters":{},"ValidationType":"required"}]},{“FieldName”:”Email”,”ReplaceValidationMessageContents”:false,”ValidationMessageId”:”Email_validationMessage”,”ValidationRules”:[{"ErrorMessage":"Email  required.","ValidationParameters":{},"ValidationType":"required"}]}],”FormId”:”form0″,”ReplaceValidationSummary”:true,”ValidationSummaryId”:”validationSummary”});


The client-side components contain the array of validators to apply to each form element.  It maps the property of the model object(which is equivalent to the ID of the control), mapping these to the validation rules to validate against.  For instance, you see a lot of required validators, which refers to a client-side implementation of each of the server-side component.  It also contains the error message to display to the user when the validation fails.


The action method to get and post the data to the view looks like the same as our server-side validation example too.  Check the example below:


[HttpGet]
public ActionResult AjaxIndex()
{
 return View(new ValidationTestClass { FirstName = “Bob”, LastName = “Anderson”, Email = “boba@test.com” });
}


[HttpPost]
public ActionResult AjaxIndex(ValidationTestClass val)
{
 if (!ModelState.IsValid)
  return View();


 return RedirectToAction(“Index”, “Home”);
}


 


First, the view that posts back fires the client-side validation first.  If it detects an error, the field is flagged with a message generated on the client-side.  If successful, the form posts back and processes the equivalent server-side validator, and if that check fires, the ModelState.IsValid property will evaluate to true.

2 comments so far

  1. w3cvalidation
    12:55 pm - 4-8-2010

    Nice information, I really appreciate the way you presented.

  2. w3cvalidation
    11:07 am - 5-12-2010

    Nice information, I really appreciate the way you presented.Thanks for sharing..

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>