ASP.NET MVC 3.0 Validation using Unobtrusive jQuery


In my previous article MVC 3.0 Custom Validation using CustomValidationAttribute, we did some serverside validation on the model when user tried to submit the page. How about making it more interactive and responsive validation for the same? Yes. We can do that using Unobtrusive jQuery. So, this article is going to take you through how we can implement the Validation in ASP.NET MVC 3.0 application using jQuery with simple steps. About ASP.NET MVC 3.0 Validation using Unobtrusive jQuery.

Learn ASP.NET MVC 3.0 Validation using Unobtrusive jQuery


Hi,

In my previous article ASP.NET MVC 3.0 Custom Validation using ValidationAttribute we went through how we can implement the server side validation in ASP.NET MVC 3.0 Application. In this article we are going to look into how we can implement validation in MVC 3.0 application using jQuery. So, there comes a question. Whether we need server side validation or not? Answer is, we need both. Because client side validation works with javscript. If the browser has disabled javascript, then the validation won't fire and there is a bigger chance that wrong data can be processed. So we will have both Server side and client side validation implemented.


However, in this article, I won't take you much on the server side validation as I had already covered this in my previous article ASP.NET MVC 3.0 Custom Validation using ValidationAttribute. I will be using the same sample project which I had attached for that and will be modifying it for this client side validation.


Step 1:
Add the following JS files in _Layout.cshtml file. _Layout.cshtml file acts as master page for MVC applications.

  1. jquery-1.5.1.min.js

  2. jquery.validate.js

  3. jquery.validate.unobtrusive.js


Step 2:

Now we are going to have our custom validation implementation done and then we will associate this validation in the model where we want to apply. I will take a simple example what I used in my previous article. I will validate the percentage fed in by the user. The value should not be less than 1 and greater than 100. For implementing the server side custom vaidation, we inherited ValidationAttribute. We will do that and for the client side validation, we need to implement IClientValidatable interface which has got a method GetClientValidationRules.



  1. Create a folder with the name ValidationRules.

  2. Create a class with the name ModelClientPercentageRangeValidationRule.cs

  3. Create a class with the name PercentageValidationAttribute.cs

  4. Add 2 member variables minPercentage and maxPercentage

  5. Now inherit the class ValidationAttribute and implement the interface IClientValidatable and a create instance of ModelClientPercentageRangeValidationRule under GetClientValidationRules method.


We need to pass the error message and minPercentage and maxPercentage.
Your ModelClientPercentageRangeValidationRule.cs should like given below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DotnetGurukulMVCUI.ValidationRules
{
public class ModelClientPercentageRangeValidationRule : ModelClientValidationRule
{
public ModelClientPercentageRangeValidationRule(string errorMessage, int minPercentage, int maxPercentage)
{
ErrorMessage = errorMessage;

ValidationType = "percentagerange";

ValidationParameters.Add("minpercentage", minPercentage);
ValidationParameters.Add("maxpercentage", maxPercentage);
}

}
}

If you see the above code, the name and parameters names should be in lowercase. Else it will throw an error when we implement the jQuery validation. Because, jQuery Unobtrusive always expects to be in lower case.


Your PercentageValidationAttribute.cs file should have the code like given below



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace DotnetGurukulMVCUI.ValidationRules
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false,
Inherited = true)]
public class PercentageValidationAttribute : ValidationAttribute, IClientValidatable
{
private int minPercentage = 1;
private int maxPercentage = 100;

public PercentageValidationAttribute() : base("Percenatge is not valid.")
{
}

public override bool IsValid(object value)
{
int percentage = (int)value;
if (percentage < this.minPercentage || percentage > this.maxPercentage)
return false;
return true;
}


#region IClientValidatable Members
public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientPercentageRangeValidationRule
("Percentage should be between 1 and 100.", this.minPercentage, this.maxPercentage);
yield return rule;
}
#endregion
}
}

We will have both IsValid and GetClientValidationRules because IsValid works on the server side and GetClientValidationRules works on the client side. As I said earlier, it's better to have both server side and client side validations in place.


Step 3:

In this step we are going to create a model and we are going to associate the validation which we had created. Under the models directory, create a class file with the name AccountDetails.cs and make it public.

  1. Add 3 members, Name, AccountType and InterrestPercentage and mark it with required attribute.

  2. Now, we are going to apply the custom attribute which we had created to validate the percentage and we will apply on InterrestPercentage member of AccountDetails class.

After doing the all the changes, your AccountDetails.cs file should look like given below.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using DotnetGurukulMVCUI.ValidationRules;

namespace DotnetGurukulMVCUI.Models
{
public class AccountDetails
{
///
/// Holds the Account Holder Name
///

[Required(ErrorMessage="Name is requried")]
public string Name { get; set; }
///
/// Holds the Account Type
///

[Required(ErrorMessage = "Account type is requried")]
public string AccountType { get; set; }
///
/// Holds the Interest Percentage
///

[Required(ErrorMessage = "Percentage is required.")]
[PercentageValidation]
public int InterestPercentage { get; set; }
}
}



Step 4:

Now we are going to work on the Index.csthml file where we need to handle the validation. I will go ahead and remove the existing Index.cshtml content and I will add the controls which reflects the AccountDetails.cs model. I haven't added the cshtml content here as it may break the DNS look. You can find that in the project which I had attached with this article.


There are 2 steps which are involved in making the validation script to work on the client side.

  1. Create a custom javascript method that does the client validation on input values.

  2. Add the method to the list of unobtrusive validators.

The custom javascript method will look like


    
jQuery.validator.addMethod('compareIt',
function (value, element, params) {
if (parseInt(value) >= params.minpercentage && parseInt(value) <= params.maxpercentage)
return true
else
false;
},
'');

and the code for adding it to the validators will look like

jQuery.validator.unobtrusive.adapters.add('percentagerange',['minpercentage', 'maxpercentage'],
function (options) {
options.rules['compareIt'] = options.params;
options.messages['compareIt'] = options.message;
}

There are couple of things which you should remember. If you had noticed, the name and the parameters are all in smaller case


	jQuery.validator.unobtrusive.adapters.add('percentagerange',['minpercentage', 'maxpercentage']

percentagerange is the name what we gave in ModelClientPercentageRangeValidationRule class file and ther parameters minpecentage and maxpercentage are the parameters what we had added as the parameters. Now you can test the application by pressing F5 and try with different values for Interest Percentage. You can see the output which is very responsive to the user when compared to my previous post about Server Side Validation in ASP.NET MVC 3.0


This ends the article on implementing jQuery Validation in ASP.NET MVC Applidation. Please feel free to post your comments and suggestions. I herewith attached the sample project which contains the code for this article. You can explore that too. See you soon with my next article.


Attachments

  • MVC Validation using jQuery (43524-12345-DotnetGurukulMVCjQuery.rar)
  • Comments

    Guest Author: Jai Santosh21 Jun 2012

    Great article i was looking for explanation



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: