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.
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. 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. 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 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. 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. After doing the all the changes, your AccountDetails.cs file should look like given below. 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. The custom javascript method will look like There are couple of things which you should remember. If you had noticed, the name and the parameters are all in smaller case 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.Learn ASP.NET MVC 3.0 Validation using Unobtrusive jQuery
Hi,
Step 1:
Add the following JS files in _Layout.cshtml file. _Layout.cshtml file acts as master page for MVC applications.
Step 2:
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);
}
}
}
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
{
var rule = new ModelClientPercentageRangeValidationRule
("Percentage should be between 1 and 100.", this.minPercentage, this.maxPercentage);
yield return rule;
}
#endregion
}
}
Step 3:
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:
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;
} jQuery.validator.unobtrusive.adapters.add('percentagerange',['minpercentage', 'maxpercentage']
Great article i was looking for explanation