Saturday, October 12, 2013

jQuery dynamic validation error messages

I am not a champ at asp.net mvc and found myself struggling with a task that at first I thought will be trivial, below is how I got through it :)

I wrote a custom validation attribute and needed to show validation messages as per values entered. Below is stripped down version of what I ended up doing:

Below lines add validation attribute named checkagainstmaxsumvalue that checks values of two fields and decides error messages dynamically

jQuery.validator.unobtrusive.adapters.add("checkagainstmaxsumvalue", ["dependentproperty1", "dependentproperty2"], function (options) {

    options.rules['checkagainstmaxsumvalue'] = {
        prop1: options.params['dependentproperty1'],
        prop2: options.params['dependentproperty2']
    };

});

jQuery.validator.addMethod("checkagainstmaxsumvalue", function (value, element, params) {
        var result = true;
        var prop1 = parseInt($('#' + params['prop1']).val(), 10);
        var prop2 = parseInt($('#' + params['prop2']).val(), 10);

        var errMsg = getErrorMessage(prop1, prop2);
        if (errMsg) {
            result = false;
        }
        return result;

    }, function (params, element) {
        var prop1 = parseInt($('#' + params['prop1']).val(), 10);
        var prop2 = parseInt($('#' + params['prop2']).val(), 10);
        return getErrorMessage(prop1, prop2);
    }
);

//Validation logic here, returns error message if validation fails 
//and empty string if success
function getErrorMessage(prop1, prop2) {
    var errMsg = "";
    if (prop1 < 20 && prop2 < 20) {
        errMsg = "Either of prop1 and prop2 should be greater than 20";
    } else if (prop1 + prop2 > 30) {
        errMsg = "Sum of prop1 and prop2 should be less than equal to 30";
    }
    return errMsg;

}

This all I did after reading below answer at every developer's life saver site SO :)
http://stackoverflow.com/questions/13352626/dynamic-jquery-validate-error-messages-with-addmethod-based-on-the-element#answer-13352987

This worked perfectly fine in my case but still there is concern that validation logic executes twice, once for deciding message and once for actual verification. This sounds a bit overkill but till now I didn't have a better option.

About Me

My photo
Delhi, India
Fun, music, travel and nature loving, always smiling, computer addict!!