2

So, I took some code from this Microsoft provided Example which allows me to use the jquery validate unobtrusive library to parse validation error message returned from my server and display them in the UI. They have a video demonstrating this. So, here is the piece of Javascript code I'm using:

   $.validator.addMethod("failure", function () { return false; });
    $.validator.unobtrusive.adapters.addBool("failure");
    $.validator.unobtrusive.revalidate = function (form, validationResult) {
        $.removeData(form[0], 'validator');
        var serverValidationErrors = [];
        for (var property in validationResult) {
            //var elementId = property.toLowerCase();
            var item = form.find('#' + property);
            if (item.length < 1) { item = form.find('#' + property.replace('.', '_')); }
            serverValidationErrors.push(item);
            item.attr('data-val-failure', validationResult[property].join(', '));
            jQuery.validator.unobtrusive.parseElement(item[0]);
        }
        form.valid();
        $.removeData(form[0], 'validator');
        $.each(serverValidationErrors, function () {
            this.removeAttr('data-val-failure');
            jQuery.validator.unobtrusive.parseElement(this[0]);
        });
    };

So then after a AJAX form post in the handle error function I would do something like this:

$.validator.unobtrusive.revalidate(form, { 'PhysicalAddress.CityName': ['You must select a valid city'] });

Where PhysicalAddress.CityName is the name of my viewmodel property and html input field. So, it knows to put the validation message next to the correct html element.

This works 1 time. Then when they hit submit again and my code calls the unobtrusive.revalidate method again.. it doesnt work. It only shows the validation message one time then after that the validation message disappears for good.

Does anyone have any idea as to why this might be happening?.. I stepped through the revalidate method and no errors were thrown and everything seems like it should work.. but the unobtrusive library for some reason is not re-binding the validation error message.

Thanks

1 Answer 1

3
+50

Probably this behavior depends on a known problem of the jQuery validation plugin: dynamically adding new validation rules for elements works just once! Further attempts are rejected because the plugin think they are a duplicated attempt to define the already defined rules.

This is the reason why the $.validator.unobtrusive.parse doesn't work when you add newly created content (when for instance you add a new row to a collection of items). There is a patch for the $.validator.unobtrusive.parse that you might try to apply also to the revalidate function....but it is better to rewrite it from scratch in a different way. The revalidate function usse the validation plugin just to place at the right place all validation errors, then it tries to reset the state of the validation plugin. However, deleting the validator object from the form is not enough to cancel all job done since there is another object contained in the form.data('unobtrusiveValidation'), where form is a variable containing the form being validated...This data are not reset by the revalidate function...and CANNOT be reset since resetting them would cause the cancellation of ALL client side validation rules.

Maybe this problem has been solved in the last version of the validation plugin, so try to update to the last version with nuget.

If this doesn't solve your issue I can pass you an analogous function implemented in a completely different way(it mimics what the server does on the server side to show server side errors). It will be contained in the upcoming version of the Mvc Controls toolkit. However, if you give me a couple of days (I will be very busy for 2 days) I can extract it from there with its dependencies so you can use it. Let me know if you are interested.

Below the code I promised. It expects an array whose elements are:

{
    id:id of the element in error
    errors:array of strings errors associated to the element
}

It accepts several errors for each element but just display di first one for each element id is different from the name because . [ ] an other special char are replaced by _

You can transform name into id on the sever with

htmlName.Replace('$', '_').Replace('.', '_').Replace('[', '_').Replace(']', '_');

or on the client in javascript with:

name.replace(/[\$\[\]\.]/g, '_');

function remoteErrors(jForm, errors) {
    //////////
    function inner_ServerErrors(elements) {
        var ToApply = function () {
            for (var i = 0; i < elements.length; i++) {
                var currElement = elements[i];
                var currDom = $('#' + currElement.id);
                if (currDom.length == 0) continue;
                var currForm = currDom.parents('form').first();
                if (currForm.length == 0) continue;

                if (!currDom.hasClass('input-validation-error'))
                    currDom.addClass('input-validation-error');
                var currDisplay = $(currForm).find("[data-valmsg-for='" + currElement.name + "']");
                if (currDisplay.length > 0) {
                    currDisplay.removeClass("field-validation-valid").addClass("field-validation-error");
                    replace = $.parseJSON(currDisplay.attr("data-valmsg-replace")) !== false;
                    if (replace) {
                        currDisplay.empty();
                        $(currElement.errors[0]).appendTo(currDisplay);
                    }
                }
            }
        };
        setTimeout(ToApply, 0);
    }
    /////////
    jForm.find('.input-validation-error').removeClass('input-validation-error');
    jForm.find('.field-validation-error').removeClass('field-validation-error').addClass('field-validation-valid');
    var container = jForm.find("[data-valmsg-summary=true]");
    list = container.find("ul");
    list.empty();
    if (errors.length > 0) {
        $.each(errors, function (i, ival) {
            $.each(ival.errors, function (j, jval) {
                $("<li />").html(jval).appendTo(list);
            });

        });
        container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
        inner_ServerErrors(errors);
        setTimeout(function () { jForm.find('span.input-validation-error[data-element-type]').removeClass('input-validation-error') }, 0);
    }
    else {
        container.addClass("validation-summary-valid").removeClass("validation-summary-errors");
    }
}
function clearErrors(jForm) {
    remoteErrors(jForm, []);
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.