Search code examples
asp.net-mvc-3validationunobtrusive-javascripthidden-field

MVC3 unobtrusive validation move validation to custom element


Serverside I render a hiddenfield, I then use a jquery widget called flexbox to create a combobox, it creates a input element client side and copies the selected ID (Not text) to the hidden field once you select something in the box.

The problem is that the validation code adds a classname to the hiddenfield when something is wrong with validation, I want it to be added to the input element, can I somehow listen to when the classname is added, or somehove hook into the event and move the classname to the inputfield.

This works but its ugly as hell, would like a better solution

var oldClass = $hdn.attr('class');

setInterval(function () {
    if (oldClass != $hdn.attr('class')) {
        $input.removeClass(oldClass);
        oldClass = $hdn.attr('class');
        $input.addClass($hdn.attr('class'));
    }
}, 200);

Thanks.


Solution

  • Thanks to Counsellorben i found a good solution, I did it in a slightly different way though. First i override the default methods in my master object contructor which is is constructed at document.ready. document.ready is however too late and your methods will not trigger when doing a triggering validation from form.valid() it will however trigg when doing a submit (very strange) this code works both for submit and triggered from script

    (function() {
        var highlight = $.validator.defaults.highlight;
        var unhighlight = $.validator.defaults.unhighlight;
    
        $.validator.setDefaults({
            highlight: function (element, errorClass, validClass) {
                if ($(element).attr("data-val-visualId") != null) {
                    element = $("#" + $(element).attr("data-val-visualId"))[0];
                }
                highlight(element, errorClass, validClass);
            },
            unhighlight: function (element, errorClass, validClass) {
                if ($(element).attr("data-val-visualId") != null) {
                    element = $("#" + $(element).attr("data-val-visualId"))[0];
                }
                unhighlight(element, errorClass, validClass);
            }
        });
    })();