Over a million developers have joined DZone.

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

DZone's Guide to

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

· ·
Free Resource

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; }    
  public int Credits { get; set; }

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:

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

    <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 the call for EnableClientValidation of the HtmlHelper class.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}