MVC3 jquery.validate.unobtrusive覆盖选项而不编辑源代码?

时间:2012-03-29 22:59:45

标签: jquery asp.net-mvc-3 validation unobtrusive-validation

只是想知道在使用mvc3 jquery.validate.unobtrusive时是否有办法覆盖高亮和unhighlight选项而不编辑源js文件......

我已经尝试过:

var elementToValidate = $(element);
        var form = $(element.form);
        if (form.length) {
            //elementToValidate.valid();
            form.validate({
                highlight: function (element, errorClass, validClass) {
                    $(element).removeClass(errorClass);
                    $(element).closest('td').addClass('alert-error error');
                }, unhighlight: function (element, errorClass, validClass) {
                    $(element).removeClass(errorClass);
                    $(element).closest('td').addClass('alert-error error');
                }
            });
        }

但除非我从脚本中删除不显眼的库,否则不会覆盖高亮和不高亮。

如果我编辑jquery.validate.unobtrusive.js的来源它似乎工作得很完美:

function validationInfo(form) {
        var $form = $(form),
            result = $form.data(data_validation);

        if (!result) {
            result = {
                options: {  // options structure passed to jQuery Validate's validate() method
                    errorClass: "input-validation-error",
                    errorElement: "span",
                    errorPlacement: $.proxy(onError, form),
                    invalidHandler: $.proxy(onErrors, form),
                    messages: {},
                    rules: {},
                    success: $.proxy(onSuccess, form),
                    highlight: function (element, errorClass, validClass) {
                        $(element).removeClass(errorClass);
                        $(element).closest('td').addClass('alert-error error');
                    }, unhighlight: function (element, errorClass, validClass) {
                        $(element).removeClass(errorClass);
                        $(element).closest('td').addClass('alert-error error');
                    }
                },
                attachValidation: function () {
                    $form.validate(this.options);
                },
                validate: function () {  // a validation function that is called by unobtrusive Ajax
                    $form.validate();
                    return $form.valid();
                }
            };
            $form.data(data_validation, result);
        }

        return result;
    }

只是想知道是否有人想出一种方法来覆盖选项而无需修改源..

干杯

1 个答案:

答案 0 :(得分:0)

您可以更改jquery验证器默认值:

$.validator.defaults.highlight = function (element, errorClass, validClass) {
    $(element).removeClass(errorClass);
    $(element).closest('td').addClass('alert-error error');
};
$.validator.defaults.unhighlight = function (element, errorClass, validClass) {
    $(element).removeClass(errorClass);
    $(element).closest('td').addClass('alert-error error');
};

在执行onload事件之前执行此操作(即,不要在$(document).ready()中调用此函数,而是直接调用此函数。)