суббота, 26 февраля 2011 г.

Remote validation in ASP.NET MVC 2 with jQuery

In my research for CQRS concept project I want to use ASP.NET DataAnnotations for automatically support validation for my view models, but I want to use in the same way validation rules on client side, in standard DataAnnotations it supports client code associations for standard attributes provided with ASP.NET script. Unfortunately, in current version of ASP.NET MVC 2 doesn't support remote validation using ajax call, in MvcContrib project we can take implementation, but it doesn't meet my requirements and during testing I find some cases where it completely even doesn't be called. Simple case was when we submit form, so we can't process validation result in JavaScript callback, because page have been already sent.
I create additional params, so right now we can control processing remote validation, using jQuery synchronous ability.
JavaScript validation function:
Sys.Mvc.ValidatorRegistry.validators.remote = function (rule) {
    var url = rule.ValidationParameters.url;
    var parameterName = rule.ValidationParameters.parameterName;
    var isAsync = rule.ValidationParameters.isAsync=='true' || false;
    var message = rule.ErrorMessage;
    var result = true;

    var onComplete = function (responseData) {
        var lowerData = responseData.toLowerCase();
        if (lowerData != 'true') {
            var newMessage = (lowerData == 'false' ? message : responseData);
            result = newMessage;

    return function (value, context) {
        if (!value || !value.length) {
            return true;

        if (context.eventName == 'blur') {
            return true;

        var ajaxCallParam = {
            url: url,
            async: isAsync,
            data: $.param([{ name: parameterName, value: value}])

        if (isAsync) {
            ajaxCallParam.success = onComplete;

        var responseData = $.ajax(ajaxCallParam);

        if (!isAsync) {

        return result;
Where custom Remote validation attribute:
public sealed class RemoteValidationAttribute : ValidationAttribute
    public string Action { get; set; }
    public string Area { get; set; }
    public string Controller { get; set; }
    public string ParameterName { get; set; }
    public string RouteName { get; set; }

    public bool IsAsync { get; set; }

    public override bool IsValid(object value)
        return true;
With actual Remote Validator:
public class RemoteValidator : DataAnnotationsModelValidator
    public RemoteValidator(ModelMetadata metadata, ControllerContext context,
                           RemoteValidationAttribute attribute) :
                               base(metadata, context, attribute)

    public override IEnumerable GetClientValidationRules()
        var rule = new ModelClientValidationRule
                           ErrorMessage = ErrorMessage,
                           ValidationType = "remote"

        rule.ValidationParameters["url"] = GetUrl();
        rule.ValidationParameters["parameterName"] = Attribute.ParameterName;
        rule.ValidationParameters["isAsync"] = Attribute.IsAsync.ToString().ToLower();
        return new[] {rule};

    private string GetUrl()
        var rvd = new RouteValueDictionary
                                           {"area", Attribute.Area ?? string.Empty },
                                           {"controller", Attribute.Controller},
                                           {"action", Attribute.Action}

        var virtualPath = RouteTable.Routes.GetVirtualPath(ControllerContext.RequestContext,
                                                           Attribute.RouteName, rvd);
        if (virtualPath == null)
            throw new InvalidOperationException("No route matched!");

        return virtualPath.VirtualPath;
That we have to register on application start up:

ASP.NET MVC 3 presented remote validation out of box, but previous implementation still need such type of functionality. My implementation based on original post by Brad Wilson.

Thank you, and I am always waiting for any feedback.

7 коммент.:

Анонимный комментирует...

Great job. Because i'm a newbie in this area this topic was the most useful for me.

Unknown комментирует...

I really like examining and also following ones write-up when i locate them incredibly beneficial and also fascinating.
That write-up is usually just as beneficial along with fascinating.Verification and Validation both are independent type of testing. Obviously,
If we look both of these activities as a whole, we can also call it testing.

software validation

Unknown комментирует...

I also tell my team members to spend qaulity time doing analysis of the work they do. Do not spend the entire day in just doing testing.
Spending everyday sometime on Analysis will help them
to move in the right direction in the work and also helps them to see in a bigger and broader perspective of the work.
Finally, just spend good amount of time in planning, reviews and analysis, the execution will be done like in no time.

<a href="http://softwarevalidation.skyrock.com/3242076685-software-validation.html
>software validation</a>

Unknown комментирует...

Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog. Recently I did Software Testing Training in Chennai at a reputed training institutes. This is really useful for me to make a bright future in IT field.

marsbahis комментирует...


Анонимный комментирует...

tül perde modelleri
sms onay
vodafone mobil ödeme bozdurma
Ankara evden eve nakliyat
Trafik sigortasi
Kurma Web Sitesi
aşk kitapları

Анонимный комментирует...

Smm Panel
smm panel
instagram takipçi satın al
tiktok jeton hilesi

Отправить комментарий