Click here to Skip to main content
15,880,503 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
14 Sep 2010CPOL2 min read 33.1K   7   4
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:

C#
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; }    
  [Range(1,4)]
  public int Credits { get; set; }

  #endregion
}

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:

C#
[HttpPost]
public ActionResult Create(Course course)
{
  try
  {
    if (ModelState.IsValid)
    {
      _courses.Add(course);
      return RedirectToAction("Index");
    }
    return View();
  }
  catch
  {
    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:

ASP.NET
<%@ 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">
    Create
</asp:Content>

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

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

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:

ASP.NET
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<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>
</head>
<body>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>My MVC Application</h1>
            </div>
            <div id="logindisplay">
                <% Html.RenderPartial("LogOnUserControl"); %>
            </div> 
            <div id="menucontainer">
                <ul id="menu">              
                    <li><%: Html.ActionLink("Home", "Index", "Home")%></li>
                    <li><%: Html.ActionLink("About", "About", "Home")%></li>
                </ul>
            </div>
        </div>

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

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

Validations in Action

Summary

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.

License

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


Written By
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: http://www.gilfink.net

Comments and Discussions

 
GeneralA blog post... Pin
Dave Kreskowiak14-Sep-10 3:52
mveDave Kreskowiak14-Sep-10 3:52 
GeneralRe: A blog post... Pin
Gil Fink14-Sep-10 5:48
Gil Fink14-Sep-10 5:48 
GeneralRe: A blog post... Pin
Dave Kreskowiak14-Sep-10 20:01
mveDave Kreskowiak14-Sep-10 20:01 
GeneralCode Formatting Sucks!!! Pin
Kunal Chowdhury «IN»13-Sep-10 23:33
professionalKunal Chowdhury «IN»13-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.