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

September 14, 2010

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. How to Enable Client Side Validation in ASP.NET MVC 2One 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.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

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>

3 comments

  1. Craig StuntzSeptember 15, 2010 ב 16:30

    If you use script paths like this in your master page:

       ../../Scripts/jquery-1.4.1.js

    Then they will break on pages which don’t happen to fit the /controller/action URI pattern (e.g., /controller/action). So instead do:

       &lt;%: Url.Content(“~/Scripts/jquery-1.4.1.js”) %&gt;

    …which gives an absolute path which always works.

    Reply
  2. Gil FinkSeptember 15, 2010 ב 17:59

    @Craig Stuntz,
    Thanks for your comment.
    I’m familiar with the problems of absolute and relative paths problems (hopefully like every other web developer).
    This is a very simple example of how to use the client side validaiton feature of MVC framework.

    Reply
  3. Derek MorrisonSeptember 17, 2010 ב 19:23

    It looks like you don’t need a couple of the JavaScript includes (jquery-1.4.1.js and jquery.validate.js) for this to work in its simplest form. If you want to use jQuery for validation and exclude the Microsoft libraries, then you’d need to include these two files, but also MicrosoftMvcJQueryValidation.js.

    http://weblogs.asp.net/imranbaloch/archive/2010/08/23/asp-net-mvc-jquery-validation-and-validationsummary.aspx

    Reply