Click here to Skip to main content
Click here to Skip to main content

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 have 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

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

  #endregion
}

 

As you can see the course require 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:

[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:

<%@ 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:

<%@ 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 the 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)

About the Author

Gil Fink
Architect Sela Group
Israel Israel
Gil Fink is an expert in web development and Microsoft web and data platforms. He works as a senior consultant and architect at Sela Group. 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 a co-author of several Microsoft Official Courses and training kits and the founder of Front-End.IL meetup. You can read his publications at his website: http://www.gilfink.net
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralA blog post... PinmvpDave Kreskowiak14-Sep-10 3:52 
GeneralRe: A blog post... PinmemberGil Fink14-Sep-10 5:48 
GeneralRe: A blog post... PinmvpDave Kreskowiak14-Sep-10 20:01 
GeneralCode Formatting Sucks!!! PinmentorKunalChowdhury13-Sep-10 23:33 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 14 Sep 2010
Article Copyright 2010 by Gil Fink
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid