Click here to Skip to main content
13,093,944 members (54,538 online)
Click here to Skip to main content
Add your own
alternative version


7 bookmarked
Posted 14 Sep 2010

How to Enable Client Side Validation in ASP.NET MVC 2

, 14 Sep 2010
Rate this:
Please Sign up or sign in to vote.
A post that explains how to enable client side validation in ASP.NET MVC 2.

Last night, I was teaching MVC Framework as part of an ASP.NET course. One of the things that I showed the students was how to use data annotations for server side validation. I got a question about how to enable client side validation in MVC 2 and decided to write about it in a post. So here it goes…

MVC Server Side Validation

In MVC 1, we didn’t have client side validation out of the box. In order to achieve validation, we needed to use one of two ways:

  • Implement the IDataErrorInfo interface. In this way, every model entity which needs validation has to implement that interface.
  • Decorate every model entity with data annotations for validations. This is my preferred way since it is more elegant and you don’t need to hold the validation implementation inside your model entities.

These ways are server side validation. For client side validation, we needed to use client side libraries such as jQuery Validator plug-in and write the client validation code. In MVC 2, this was made easier to implement.

Enabling Client Side Validation in MVC 2

Let's take a look at an entity which is decorated with data annotations:

public class Course
  #region Properties

  public int CourseID { get; set; }

  [Required(ErrorMessage = "Course title is required")]
  public string Title { get; set; }

  [StringLength(5, ErrorMessage = "Course can have up to 5 days")]
  public string Days { get; set; }    
  public DateTime Time { get; set; }
  public string Location { get; set; }    
  public int Credits { get; set; }


As you can see, the course requires a title, its credit needs to be between 1 to 4 and the Days property has length of maximum 5 characters. In the courses controller, I want to make validation so I hook up the server side validation like I was doing in MVC 1 in the controller:

public ActionResult Create(Course course)
    if (ModelState.IsValid)
      return RedirectToAction("Index");
    return View();
    return View();

The ModelState.IsValid property will trigger the validation on the entity and we will get server side validation. If we want to get client side validation, we will have to activate it on the view. In MVC 2, we have another extension method on the HtmlHelper class that will help us to do so. The method is called EnableClientValidation. The create view will look like:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 

Inherits="System.Web.Mvc.ViewPage<MvcApplication2.Models.Course>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% Html.EnableClientValidation(); %>
    <% using (Html.BeginForm()) {%>
        <%: Html.ValidationSummary(true) %>

            <div class="editor-label">
                <%: Html.LabelFor(model => model.CourseID) %>
           <div class="editor-field">
                <%: Html.TextBoxFor(model => model.CourseID) %>
                <%: Html.ValidationMessageFor(model => model.CourseID) %>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Title) %>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Title) %>
                <%: Html.ValidationMessageFor(model => model.Title) %>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Days) %>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Days) %>
                <%: Html.ValidationMessageFor(model => model.Days) %>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Time) %>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Time) %>
                <%: Html.ValidationMessageFor(model => model.Time) %>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Location) %>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Location) %>
                <%: Html.ValidationMessageFor(model => model.Location) %>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Credits) %>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Credits) %>
                <%: Html.ValidationMessageFor(model => model.Credits) %>
                <input type="submit" value="Create" />
    <% } %>
        <%: Html.ActionLink("Back to List", "Index") %>

If you will run the application now, you will see that even though you explicitly enabled client side validation in the view, it won’t run. The reason for that is that you need to link the validation JavaScript files to enable validation. Here are the JavaScript files you need to link (which exists by default in every not empty MVC 2 application):

  • jquery-1.4.1.js
  • jquery.validate.js
  • MicrosoftAjax.js
  • MicrosoftMvcAjax.js
  • MicrosoftMvcValidation.js

The place to link them is of course the master page so here is the master page implementation:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 

<html xmlns="">
<head runat="server">
    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>  
    <script src="../../Scripts/jquery.validate.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>     
    <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>My MVC Application</h1>
            <div id="logindisplay">
                <% Html.RenderPartial("LogOnUserControl"); %>
            <div id="menucontainer">
                <ul id="menu">              
                    <li><%: Html.ActionLink("Home", "Index", "Home")%></li>
                    <li><%: Html.ActionLink("About", "About", "Home")%></li>

        <div id="main">
            <asp:ContentPlaceHolder ID="MainContent" runat="server" />
            <div id="footer">

That is it. Now you have client side validation hooked in your MVC 2 web application.

Validations in Action


In MVC 2, we have client side validation implemented inside the framework. All we have to do is to link some JavaScript files and to add to the relevant view to call for EnableClientValidation of the HtmlHelper class.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Gil Fink
Technical Lead sparXys
Israel Israel
Gil Fink is a web development expert and ASP.Net/IIS Microsoft MVP. He is the founder and owner of sparXys. He is currently consulting for various enterprises and companies, where he helps to develop Web and RIA-based solutions. He conducts lectures and workshops for individuals and enterprises who want to specialize in infrastructure and web development. He is also co-author of several Microsoft Official Courses (MOCs) and training kits, co-author of "Pro Single Page Application Development" book (Apress) and the founder of Front-End.IL Meetup. You can read his publications at his website:

You may also be interested in...

Comments and Discussions

GeneralA blog post... Pin
Dave Kreskowiak14-Sep-10 3:52
mvpDave Kreskowiak14-Sep-10 3:52 
GeneralRe: A blog post... Pin
Gil Fink14-Sep-10 5:48
memberGil Fink14-Sep-10 5:48 
GeneralRe: A blog post... Pin
Dave Kreskowiak14-Sep-10 20:01
mvpDave Kreskowiak14-Sep-10 20:01 
GeneralCode Formatting Sucks!!! Pin
KunalChowdhury13-Sep-10 23:33
mentorKunalChowdhury13-Sep-10 23:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170813.1 | Last Updated 14 Sep 2010
Article Copyright 2010 by Gil Fink
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid