繁体   English   中英

将qTip与MVC3和jQuery验证(errorPlacement)集成

[英]Integrating qTip with MVC3 and jQuery Validation (errorPlacement)

我正在使用MVC3开发一个proyect,并且试图将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;
});

很好的解决方案,谢谢,我已经在我的应用程序中使用了它。

...要进一步添加,而不是直接修改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毫不客气的客户端验证

替代解决方案

我的第一个解决方案有效,但在某些情况下也引起了一些意外的行为。 我通过在同一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;
});

我的解决方案-可以在单独的.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;
    }
});

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

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

2)其次,在脚本上找到函数 validateInfo (form),并用qTip提供的一种或您选择的任何一种来替换options结构中的errorPlacement指令。

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;
}

使用MantisimoAJC答案(感谢他),我编写了以下脚本,它可以正常运行,没有任何问题,但是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进行了测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM