13

我正在使用 MVC3 开发一个项目,并且我正在尝试将 qTip2 与 jQuery 验证集成,以便将错误显示为浮动提示。我遇到的问题是,显然在表单验证上调用 errorPlacement 没有做任何事情,猜测它与 MVC 处理它的方式有关。

基本上,我想要做的是使用 MVC3 和 jQuery(注释)之间的集成验证,但也与 qTip 集成以更改错误消息的显示方式。

我已经搜索过了,我能找到的最好的结果是有人建议修改 jquery.validate.unobtrusive.js - onError 函数,但我检查了它,不知道如何正确修改它,而且更喜欢没有的解决方案要求我更改现有脚本。

感谢您的帮助。

到目前为止我所拥有的:

我的模型:

public class User
{
    [Required]
    public string Id { get; set; }

        [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    public string FirstName { get; set; }

    public string SecondName { get; set; }

    public string LastName { get; set; }
}

我认为我的javascript:

$('#Form').validate({
    errorClass: "errormessage",
    errorClass: 'error',
    validClass: 'valid',
    errorPlacement: function (error, element) {
        // Set positioning based on the elements position in the form
        var elem = $(element),
            corners = ['left center', 'right center'],
            flipIt = elem.parents('span.right').length > 0;

        // Check we have a valid error message
        if (true) {
            // Apply the tooltip only if it isn't valid
            elem.filter(':not(.valid)').qtip({
                overwrite: false,
                content: error,
                position: {
                    my: corners[flipIt ? 0 : 1],
                    at: corners[flipIt ? 1 : 0],
                    viewport: $(window)
                },
                show: {
                    event: false,
                    ready: true
                },
                hide: false,
                style: {
                    classes: 'ui-tooltip-red' // Make it red... the classic error colour!
                }
            })

            // If we have a tooltip on this element already, just update its content
            .qtip('option', 'content.text', error);
        }

        // If the error is empty, remove the qTip
        else { elem.qtip('destroy'); }
    },
    success: $.noop // Odd workaround for errorPlacement not firing!
})

$('#Form').submit(function () {
    if (!$(this).valid())
        return false;

    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        beforeSend: function () {
        },
        success: function (result) {
        },
        error: function (result) {
        }
    });
    return false;
});
4

5 回答 5

13

很好的解决方案,谢谢,我在我的应用程序中使用了这个。

...进一步补充,我没有直接修改 jquery.validate.unobtrusive.min.js 文件,而是使用以下内容来修改不显眼验证的默认行为。

$(document).ready(function () {

            var settngs = $.data($('form')[0], 'validator').settings;
            settngs.errorPlacement = function(error, inputElement) {
                // Modify error placement here
            };
});

急切地执行 ASP.NET MVC 3 不显眼的客户端验证

于 2011-11-27T20:34:20.917 回答
11

替代解决方案

我的第一个解决方案有效,但在某些情况下也引起了一些意想不到的行为。我通过在同一个 js 文件中包含onError函数上的 errorPlacement 代码来修复:

function onError(error, inputElement) {  // 'this' is the form element
    var container = $(this).find("[data-valmsg-for='" + inputElement[0].name + "']"),
        replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;

    container.removeClass("field-validation-valid").addClass("field-validation-error");
    error.data("unobtrusiveContainer", container);

    if (replace) {
        container.empty();
        error.removeClass("input-validation-error").appendTo(container);
    }
    else {
        error.hide();
    }

    var element = inputElement;
    // Set positioning based on the elements position in the form
    var elem = $(element),
                        corners = ['left center', 'right center'],
                        flipIt = elem.parents('span.right').length > 0;

    // Check we have a valid error message
    if (!error.is(':empty')) {
        // Apply the tooltip only if it isn't valid
        elem.filter(':not(.valid)').qtip({
            overwrite: false,
            content: error,
            position: {
                my: corners[flipIt ? 0 : 1],
                at: corners[flipIt ? 1 : 0],
                viewport: $(window)
            },
            show: {
                event: false,
                ready: true
            },
            hide: false,
            style: {
                classes: 'ui-tooltip-red' // Make it red... the classic error colour!
            }
        })

        // If we have a tooltip on this element already, just update its content
        .qtip('option', 'content.text', error);
    }

    // If the error is empty, remove the qTip
    else { elem.qtip('destroy'); }
}

然后你可以提交一个表单,以这种方式检查验证:

$('#frm').submit(function () {
    if (!$(this).valid())
        return false;

    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        beforeSend: function () {
        },
        success: function (result) {
        },
        error: function (result) {
        }
    });
    return false;
});
于 2011-08-09T22:54:32.740 回答
5

我的解决方案 - 可以在单独的 .js 文件中使用,如果放在母版页中,则适用于整个站点。

$(document).ready(function () {
    //validation - make sure this is included after jquery.validate.unobtrusive.js
    //unobtrusive validate plugin overrides all defaults, so override them again
    $('form').each(function () {
        OverrideUnobtrusiveSettings(this);
    });
    //in case someone calls $.validator.unobtrusive.parse, override it also
    var oldUnobtrusiveParse = $.validator.unobtrusive.parse;
    $.validator.unobtrusive.parse = function (selector) {
        oldUnobtrusiveParse(selector);
        $('form').each(function () {
            OverrideUnobtrusiveSettings(this);
        });
    };
    //replace validation settings function
    function OverrideUnobtrusiveSettings(formElement) {
        var settngs = $.data(formElement, 'validator').settings;
        //standard qTip2 stuff copied from sample
        settngs.errorPlacement = function (error, element) {
            // Set positioning based on the elements position in the form
            var elem = $(element);


            // Check we have a valid error message
            if (!error.is(':empty')) {
                // Apply the tooltip only if it isn't valid
                elem.filter(':not(.valid)').qtip({
                    overwrite: false,
                    content: error,
                    position: {
                        my: 'center left',  // Position my top left...
                        at: 'center right', // at the bottom right of...
                        viewport: $(window)
                    },
                    show: {
                        event: false,
                        ready: true
                    },
                    hide: false,
                    style: {
                        classes: 'qtip-red' // Make it red... the classic error colour!
                    }
                })
                // If we have a tooltip on this element already, just update its content
                .qtip('option', 'content.text', error);
            }

            // If the error is empty, remove the qTip
            else { elem.qtip('destroy'); }
        };

        settngs.success = $.noop;
    }
});
于 2012-12-18T08:49:42.640 回答
2

找到了答案...发布以供参考。

1)首先,找到微软提供的脚本jquery.validate.unobtrusive.js

2) 其次,在脚本中找到函数validationInfo(form)并将options 结构中的errorPlacement指令替换为qTip 提供的指令或您选择的任何指令。

3) 对于您希望更改验证处理方式的样式和其他选项也是如此。

4) 包括所有必要的文件。

希望这可以帮助遇到类似问题的人。

示例代码:

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",
                errorClass: "error",
                errorElement: "span",
                //errorPlacement: $.proxy(onError, form),
                errorPlacement: function (onError, form) {
                    var error = onError;
                    var element = form;
                    // Set positioning based on the elements position in the form
                    var elem = $(element),
                        corners = ['left center', 'right center'],
                        flipIt = elem.parents('span.right').length > 0;

                    // Check we have a valid error message
                    if (!error.is(':empty')) {
                        // Apply the tooltip only if it isn't valid
                        elem.filter(':not(.valid)').qtip({
                            overwrite: false,
                            content: error,
                            position: {
                                my: corners[flipIt ? 0 : 1],
                                at: corners[flipIt ? 1 : 0],
                                viewport: $(window)
                            },
                            show: {
                                event: false,
                                ready: true
                            },
                            hide: false,
                            style: {
                                classes: 'ui-tooltip-red' // Make it red... the classic error colour!
                            }
                        })

                        // If we have a tooltip on this element already, just update its content
                        .qtip('option', 'content.text', error);
                    }

                    // If the error is empty, remove the qTip
                    else { elem.qtip('destroy'); }
                },
                invalidHandler: $.proxy(onErrors, form),
                messages: {},
                rules: {},
                success: $.proxy(onSuccess, form)
            },
            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;
}
于 2011-07-25T15:42:55.633 回答
0

有了Mantisimo& AJCanswers(感谢他),我编写了以下脚本,没问题,它可以正常工作,但jquery.validate.unobtrusive.js在每个提交表单中都会抛出如下错误:

$(document).ready(function () {
    var $forms = $.data($('form')[0], 'validator');
    if ($forms == undefined) return;
    var settngs = $forms.settings;
    settngs.errorPlacement = function (error, inputElement) {
        var element = inputElement;
        var elem = $(element),
            corners = ['left center', 'right center'],
            flipIt = elem.parents('span.right').length > 0;
        if (!error.is(':empty')) {
            elem.filter(':not(.valid)').qtip({
                overwrite: false,
                content: error,
                position: {
                    my: corners[flipIt ? 0 : 1],
                    at: corners[flipIt ? 1 : 0],
                    viewport: $(window)
                },
                show: {
                    event: false,
                    ready: true
                },
                hide: false,
                style: {
                    classes: 'qtip-red',
                }
            })
            .qtip('option', 'content.text', error);
        }
        else { elem.qtip('destroy'); }
    };
});

jquery.validate.unobtrusive.js 错误

我用 MVC 5 和 qtip 2.2.0 测试过

于 2014-04-06T09:45:59.437 回答