Client-Side Validation in MVC 2

 

ASP.NET MVC 2 Preview 2 now ships with client-side validation built into the box. It follows the same idea as the xVal framework whereby you can define validation rules once and have them enforced both on the server and the client.

By default, MVC uses Data Annotations which is available in System.ComponentModel.DataAnnotations on the server and the jQuery Validator plugin on the client. Much like xVal you can customize these to use whatever you want. I’m preparing some demos for next week of how to do client-side validation and since there isn’t much info on it, I’ve decided to post it.

Server-Side Validation

Server-side validation with Data Annotations works without having to take any additional steps. You decorate your model using attributes and the model binder uses this information to set the ModelState.

    public class Customer
    {
        [Required(ErrorMessage = "First name is required")]
        public string FirstName { get; set; }
        [Required(ErrorMessage = "Last name is required")]
        public string LastName { get; set; }
        public string Email { get; set; }
    }

 

On the server-side you would do the usual to check if the model state is valid and if not display validation messages back to the client:

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, Customer customer)
        {
            if (ModelState.IsValid)
            {
                // TODO: Do whatever...
                return RedirectToAction("Index");
            }
            return View(customer);
        }

 

The form is:

    <%= Html.ValidationSummary() %>
    <% using (Html.BeginForm()) {%>
 
        <%=Html.EditorForModel() %>
            <p>
                <input type="submit" value="Save" />
            </p>
    <% } %>
 

(I’m using the EditForModel which will automatically generate an input field for each property of the model. If you want finer control you can spit out individual fields or use templates).

Client-Side Validation

Client-Side validation kicks in only if it is explicitly activated in the view. To do this, you need to call EnableClientValidation as shown below:

 
    <% Html.EnableClientValidation(); %>
    <%= Html.ValidationSummary() %>
    <% using (Html.BeginForm()) {%>
 
        <%=Html.EditorForModel() %>
            <p>
                <input type="submit" value="Save" />
            </p>
    <% } %>

 

By doing this, when the form is generated, the MVC framework will add a call to JS function EnableClientValidation passing in the correct parameters based on the data annotation attributes defined on the model. Last but not least, we need to include 3 Javascript files in the View (I normally put them in Site.Master).

    <script src="../../Scripts/jquery-1.3.2.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>

 

Make sure you include the last file, where EnableClientValidation is defined. That’s all there is to it. Once you run this, your app will have both client side and server side validation using the default Data Annotations and jQuery Validator.

Download demo from here

4 thoughts on “Client-Side Validation in MVC 2

  1. Fabio Maulo

    Only as advise.
    Have a look to NHV + xVal.
    Remember that NHV know how NH work with proxy and proxy collections.

    Reply
  2. yogesh

    i have used these scripts in my master page but at runtime the error shows for every script as “Type is undefined”,”Sys is undefined”,”jQuery is undefined”

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s