Click here to Skip to main content
12,401,984 members (29,405 online)
Click here to Skip to main content
Add your own
alternative version

Stats

199.6K views
3.8K downloads
52 bookmarked
Posted

ASP.NET MVC Client Side Validation

, 1 Oct 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This article explains how to implement client-side validation in an ASP.NET MVC application.

Introduction

This article explains how to implement client-side validation in an ASP.NET MVC application. The validation is implemented using jQuery and jQuery validation plug-in (jquery.validate.min.js and jquery.validate.unobtrusive.min.js).

In the server-side validation (ASP.NET MVC Server-Side Validation), the page must be submitted via a postback to be validated on the server and if the model data is not valid, then the server sends a response back to the client. With client-side validation, the input data is checked as soon as they are submitted, so there is no postback to the server and there is no page refresh.

Using the Code

When you are developing an MVC application in Visual Studio 2012, then the client-side becomes enabled by default, but you can easily enable or disable the writing of the following app setting code snippet in the web.config file.

<configuration>
  <appSettings>  
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
</configuration>

The jQuery validation plug-in takes advantage of the Data Annotation attributes defined in the model, which means that you need to do very little to start using it. Let's create an Employee model (Employee.cs class file under the Models folder) that has two properties with Data annotation attributes.

using System.ComponentModel.DataAnnotations;
namespace ClientValidation.Models
{
    public class Employee
    {
        [Required(ErrorMessage = "Name is Requirde")]
        public string Name { get; set; }
        [Required(ErrorMessage = "Email is Requirde")]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                            @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                            @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                            ErrorMessage = "Email is not valid")]
        public string Email { get; set; }
    }
}

After that, you need to create the controller's action methods. These render views on the UI and bind a model with the view. So let's create a controller with two action methods that handle both request types (GET and POST respectively).

using System.Web.Mvc;
using ClientValidation.Models; 
namespace ClientValidation.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        } 
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(Employee model)
        {
            if (ModelState.IsValid)
            {
                ViewBag.Name = model.Name;
                ViewBag.Email = model.Email;
            }
            return View(model);
        }
    }
}

Thereafter, create a strong view that the input field binds with the model and create a JavaScript function that uses the HTML Helper extension method FieldIdFor() to get the Id of the input field and shows the input field's value in an alert message.

Add New View Screen

Figure 1.1 : Add New View Screen

Here I checked "Reference script libraries," which means Visual Studio adds these references automatically. Visual Studio adds the following code snippet to the bottom of the view.

@section Scripts 
{
    @Scripts.Render("~/bundles/jqueryval")
}

Now click on the "Add" button and the view is created as in the following code snippet:

@model ClientValidation.Models.Employee
@{
    ViewBag.Title = "Index";
}
 @if (ViewData.ModelState.IsValid)
    {
        if(@ViewBag.Name != null)
        {
            
                Name : @ViewBag.Name
                Email : @ViewBag.Email
            
        }
    } 
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true) 
    <fieldset>
        <legend>Employee</legend>

Output of Application

Let's run the application and test the following scenario.

  1. When all fields are empty:

    Validation Message when both fields are empty

    Figure 1.2: Validation Message when both fields are empty
  2. When the Name field is empty but Email is not valid:

    Validation Message when Email is not valid

    Figure 1.3 : Validation Message when Email is not valid
  3. When both fields are valid:

    All fields are valid

    Figure 1.4 All fields are valid

License

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

Share

About the Author

Sandeep Singh Shekhawat
Software Developer
India India
Sandeep Singh Shekhawat is a Software Developer. He is awarded for C# Corner MVP(2013,2014 and 2015) and CodeProject MVP (2015). His three articles at CodeProject are prize wining in article competition. His more than 10 articles has been selected Article of the Day at Microsoft ASP.NET (http://www.asp.net/) community.

You may also be interested in...

Comments and Discussions

 
QuestionNot at all Client Side Validation Pin
meeram3916-Jul-16 15:02
membermeeram3916-Jul-16 15:02 
PraiseNice Pin
vipan.net26-Feb-16 18:12
professionalvipan.net26-Feb-16 18:12 
Question[My vote of 1] Misleading article as it spends more time explaining server side validation than client side validation Pin
Dean Forant20-Oct-15 5:56
memberDean Forant20-Oct-15 5:56 
Question[My vote of 1] Not client side validation at all. Pin
Bo8321-Sep-15 17:00
memberBo8321-Sep-15 17:00 
QuestionNot client side validation at all. Pin
Bo8321-Sep-15 17:00
memberBo8321-Sep-15 17:00 
AnswerRe: Not client side validation at all. Pin
sp78463-Feb-16 14:49
membersp78463-Feb-16 14:49 
Questionwhat is difference in coding for client side and server side validation using mvc razor Pin
Member 1037441913-Jul-15 1:36
professionalMember 1037441913-Jul-15 1:36 
GeneralGood & Simple Pin
Slavimir Vesic17-Feb-15 21:04
memberSlavimir Vesic17-Feb-15 21:04 
GeneralRe: Good & Simple Pin
Sandeep Singh Shekhawat18-Feb-15 1:22
mvpSandeep Singh Shekhawat18-Feb-15 1:22 
Questionbundle not existant Pin
Member 103744989-Dec-14 9:22
memberMember 103744989-Dec-14 9:22 
AnswerRe: bundle not existant Pin
Matt U.13-Mar-15 6:09
memberMatt U.13-Mar-15 6:09 
GeneralGood One Pin
Shemeemsha RA24-Sep-14 22:54
memberShemeemsha RA24-Sep-14 22:54 
QuestionClient Side Validation Pin
Md Kamal Azhar10-Jul-14 19:21
memberMd Kamal Azhar10-Jul-14 19:21 
AnswerRe: Client Side Validation Pin
Sandeep Singh Shekhawat10-Jul-14 19:39
professionalSandeep Singh Shekhawat10-Jul-14 19:39 
QuestionValidation Pin
NithyaGopu31-Mar-14 20:34
memberNithyaGopu31-Mar-14 20:34 
AnswerRe: Validation Pin
Sandeep Singh Shekhawat31-Mar-14 20:41
professionalSandeep Singh Shekhawat31-Mar-14 20:41 
GeneralMy vote of 5 Pin
Mihai MOGA14-Feb-14 17:11
professionalMihai MOGA14-Feb-14 17:11 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat30-Aug-14 19:07
professionalSandeep Singh Shekhawat30-Aug-14 19:07 
GeneralMy vote of 5 Pin
Renju Vinod10-Feb-14 17:22
professionalRenju Vinod10-Feb-14 17:22 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat10-Feb-14 18:49
professionalSandeep Singh Shekhawat10-Feb-14 18:49 
GeneralAwesome Pin
jjlangatjose3-Feb-14 19:40
memberjjlangatjose3-Feb-14 19:40 
GeneralRe: Awesome Pin
Sandeep Singh Shekhawat3-Feb-14 19:45
professionalSandeep Singh Shekhawat3-Feb-14 19:45 
GeneralMy vote of 4 Pin
Pranay Rana3-Feb-14 1:41
memberPranay Rana3-Feb-14 1:41 
GeneralRe: My vote of 4 Pin
Sandeep Singh Shekhawat3-Feb-14 1:44
professionalSandeep Singh Shekhawat3-Feb-14 1:44 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun29-Jan-14 18:13
memberHumayun Kabir Mamun29-Jan-14 18:13 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat31-Jan-14 15:21
professionalSandeep Singh Shekhawat31-Jan-14 15:21 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 2 Oct 2014
Article Copyright 2014 by Sandeep Singh Shekhawat
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid