如何将 Twitter Bootstrap 弹出框用于 jQuery 验证通知?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8439490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:32:21  来源:igfitidea点击:

How to use Twitter Bootstrap popovers for jQuery validation notifications?

jqueryvalidationtwitter-bootstrappopover

提问by Synchro

I can make popovers appear using bootstrapeasily enough, and I can also do validations using the standard jQuery validation pluginor the jQuery validation engine, but I can't figure out how to feed one into the other.

我可以很容易地使用引导程序使弹出窗口出现,我也可以使用标准的jQuery 验证插件jQuery 验证引擎进行验证,但我不知道如何将一个输入另一个。

I think what I need is some hook which is called by the validator when it wants to display a notification, give it a closure that passes the message and the target element to a popover. This seems like a kind of dependency injection.

我认为我需要的是一些钩子,当验证器想要显示通知时调用它,给它一个闭包,将消息和目标元素传递给弹出窗口。这似乎是一种依赖注入。

All nice in theory, but I just can't figure out where that hook is, or even if one exists in either validation engine. They both seem intent on taking responsibility for displaying notifications with all kinds of elaborate options for placement, wrappers, styles when all I'm after is the error type(s) (I don't necessarily even need message text) and element it relates to. I've found hooks for the entire form, not the individual notifications.

理论上一切都很好,但我无法弄清楚那个钩子在哪里,或者即使在任一验证引擎中都存在一个钩子。当我所追求的只是错误类型(我什至不一定需要消息文本)和它相关的元素时,他们似乎都打算负责显示带有各种精心设计的放置,包装器,样式选项的通知到。我找到了整个表单的挂钩,而不是单个通知。

I much prefer validation systems that use classes to define rules, as they play nicely with dynamically created forms.

我更喜欢使用类来定义规则的验证系统,因为它们可以很好地与动态创建的表单一起使用。

Anyone have a solution or a better idea?

任何人都有解决方案或更好的主意?

采纳答案by Chris Fulstow

Take a look at the highlightand showErrorsjQuery Validator options, these will let you hook in your own custom error highlights that trigger Bootstrap popovers.

看看highlightshowErrorsjQuery Validator 选项,这些将让您挂钩触发 Bootstrap 弹出窗口的自定义错误突出显示。

回答by Kenny Meyer

This is a hands-on example:

这是一个动手示例:

$('form').validate({
    errorClass:'error',
    validClass:'success',
    errorElement:'span',
    highlight: function (element, errorClass, validClass) { 
        $(element).parents("div[class='clearfix']").addClass(errorClass).removeClass(validClass); 
    }, 
    unhighlight: function (element, errorClass, validClass) { 
        $(element).parents(".error").removeClass(errorClass).addClass(validClass); 
    }
});

enter image description here

在此处输入图片说明

It doesn't really use bootstrap popovers, but it looks really nice and is easy to achieve.

它并没有真正使用引导程序弹出窗口,但它看起来非常好并且很容易实现。

UPDATE

更新

So, to have popover validation you can use this code:

因此,要进行弹出框验证,您可以使用以下代码:

$("form").validate({
  rules : {
    test : {
      minlength: 3 ,
      required: true
    }
  },
  showErrors: function(errorMap, errorList) {
    $.each(this.successList, function(index, value) {
      return $(value).popover("hide");
    });
    return $.each(errorList, function(index, value) {
      var _popover;
      _popover = $(value.element).popover({
        trigger: "manual",
        placement: "top",
        content: value.message,
        template: "<div class=\"popover\"><div class=\"arrow\"></div><div class=\"popover-inner\"><div class=\"popover-content\"><p></p></div></div></div>"
      });
      // Bootstrap 3.x :      
      //_popover.data("bs.popover").options.content = value.message;
      // Bootstrap 2.x :
      _popover.data("popover").options.content = value.message;
      return $(value.element).popover("show");
    });
  }
});

You get something like this:

你会得到这样的东西:

enter image description here

在此处输入图片说明

Check out the jsFiddle.

查看jsFiddle

回答by Varun Singh

Chris Fulstow had it right, but it still took me a while, so heres the complete code:

Chris Fulstow 说得对,但我还是花了一段时间,所以这里是完整的代码:

This shows the popover on error, and hides the default error labels:

这显示了错误时的弹出窗口,并隐藏了默认的错误标签:

$('#login').validate({
  highlight: function(element, errClass) {
    $(element).popover('show');
  },
  unhighlight: function(element, errClass) {
    $(element).popover('hide');
  },
  errorPlacement: function(err, element) {
    err.hide();
  }
}).form();

This sets up the popover. The only thing you need from this is trigger: 'manual'

这将设置弹出窗口。您唯一需要的是触发器:'手动'

$('#password').popover({
  placement: 'below',
  offset: 20,
  trigger: 'manual'
});

The title and content attributes passed in to popover weren't working, so I specified them inline in my #password input with data-content='Minimum 5 characters' and data-original-title='Invalid Password'. You also need rel='popover' in your form.

传递给 popover 的 title 和 content 属性不起作用,所以我在 #password 输入中使用 data-content='Minimum 5 characters' 和 data-original-title='Invalid Password' 将它们内联指定。您的表单中还需要 rel='popover'。

This works, but the popover flickers upon unselecting. Any idea how to fix that?

这有效,但弹出框在取消选择时闪烁。知道如何解决这个问题吗?

回答by Jeffrey Gilbert

Here's a follow up to the excellent suggestion from Varun Singh which prevents the "flicker" issue of the validation constantly trying to "show" even though the popup is already present. I've simply added an error states array to capture which elements are showing errors and which aren't. Works like a charm!

这是对 Varun Singh 出色建议的跟进,该建议可防止验证的“闪烁”问题不断尝试“显示”,即使弹出窗口已经存在。我只是添加了一个错误状态数组来捕获哪些元素显示错误,哪些没有。奇迹般有效!

var errorStates = [];

$('#LoginForm').validate({
    errorClass:'error',
    validClass:'success',
    errorElement:'span',
    highlight: function (element, errorClass) {
        if($.inArray(element, errorStates) == -1){
            errorStates[errorStates.length] = element;
            $(element).popover('show');
        }
    }, 
    unhighlight: function (element, errorClass, validClass) {
        if($.inArray(element, errorStates) != -1){
            this.errorStates = $.grep(errorStates, function(value) {
              return value != errorStates;
            });
            $(element).popover('hide');
        }
    },
    errorPlacement: function(err, element) {
        err.hide();
    }
});

$('#Login_unique_identifier').popover({
    placement: 'right',
    offset: 20,
    trigger: 'manual'
});

$('#Login_password').popover({
    placement: 'right',
    offset: 20,
    trigger: 'manual'
});

回答by tonycoco

This jQuery extension for jQuery Validation Plugin (tested with version 1.9.0) will do the trick.

这个 jQuery 验证插件的 jQuery 扩展(用 1.9.0 版测试过)可以解决这个问题。

https://github.com/tonycoco/rails_template/blob/master/files/assets/javascripts/jquery.validate.bootstrap.js

https://github.com/tonycoco/rails_template/blob/master/files/assets/javascripts/jquery.validate.bootstrap.js

This also adds in some Rails-esk error messaging.

这也增加了一些 Rails-esk 错误消息。

回答by Codemator

Please take a look at the following:
- https://gist.github.com/3030983
I think it's the simplest of all.

请查看以下内容:
- https://gist.github.com/3030983
我认为这是最简单的。

EDIT

编辑

Code from link:

来自链接的代码:

$('form').validate({
    rules: {
        numero: {
            required: true
        },
        descricao: {
            minlength: 3,
            email: true,
            required: true
        }
    },

    showErrors: function (errorMap, errorList) {

        $.each(this.successList, function (index, value) {
            $(value).popover('hide');
        });


        $.each(errorList, function (index, value) {

            console.log(value.message);

            var _popover = $(value.element).popover({
                trigger: 'manual',
                placement: 'top',
                content: value.message,
                template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><div class="popover-content"><p></p></div></div></div>'
            });

            _popover.data('popover').options.content = value.message;

            $(value.element).popover('show');

        });

    }

});

回答by Alberto Chvaicer

I prefer to change the CSS of bootstrap. Just added the classes of jQuery validate in the right place. field-validation-error and input-validation-error

我更喜欢更改 bootstrap 的 CSS。刚刚在正确的地方添加了 jQuery 验证的类。字段验证错误和输入验证错误

    form .clearfix.error > label, form .clearfix.error .help-block, form .clearfix.error .help-inline, .field-validation-error {
  color: #b94a48;
}
form .clearfix.error input, form .clearfix.error textarea, .input-validation-error {
  color: #b94a48;
  border-color: #ee5f5b;
}
form .clearfix.error input:focus, form .clearfix.error textarea:focus, .input-validation-error:focus {
  border-color: #e9322d;
  -webkit-box-shadow: 0 0 6px #f8b9b7;
  -moz-box-shadow: 0 0 6px #f8b9b7;
  box-shadow: 0 0 6px #f8b9b7;
}

回答by Adrian P.

Many thanks for the heads up! Here is my version for Bootstrap but with Tooltips. In my opinion it's more elegant than popovers. I know the question was for popovers so please do not vote down for this reason. Maybe somebody will like it this way. I love when I'm searching for something and I found new ideas on Stackoverflow. Note: no markup on form is necessary.

非常感谢您的提醒!这是我的 Bootstrap 版本,但带有工具提示。在我看来,它比 popovers 更优雅。我知道这个问题是针对popovers的,所以请不要因为这个原因投票。也许有人会喜欢这种方式。我喜欢在寻找某些东西并在 Stackoverflow 上发现新想法时。注意:不需要在表单上进行标记。

    $('#LoginForm').validate({
        rules: {
            password: {
                required: true,
                minlength: 6
            },

            email_address: {
                required: true,
                email: true
            }
        },
        messages: {
            password: {
                required: "Password is required",
                minlength: "Minimum length is 6 characters"
            },
            email_address: {
                required: "Email address is required",
                email: "Email address is not valid"
            }
        },  
        submitHandler: function(form) {
            form.submit();
        },

        showErrors: function (errorMap, errorList) {

            $.each(this.successList, function (index, value) {
                $('#'+value.id+'').tooltip('destroy');
            });


            $.each(errorList, function (index, value) {

                $('#'+value.element.id+'').attr('title',value.message).tooltip({
                    placement: 'bottom',
                    trigger: 'manual',
                    delay: { show: 500, hide: 5000 }
                }).tooltip('show');

            });

        }

    }); 

回答by Jamie R Rytlewski

This is how I did it with Bootstrap 2.x and jQuery Validate 1.9

这就是我使用 Bootstrap 2.x 和 jQuery Validate 1.9 所做的

$('#form-register').validate({ errorElement: 'span', errorClass:'help-inline', highlight:    function (element, errorClass) {
        $(element).parent().parent().addClass('error');
    }, unhighlight: function (element, errorClass) {
        $(element).parent().parent().removeClass('error');
    }});

回答by tofirius

Here is an update to Kenny Meyer's excellent answer above. There were a couple of issues that prevented it from working for me, which I have addressed in this snippet:

这是上面 Kenny Meyer 出色回答的更新。有几个问题阻止它为我工作,我在这个片段中解决了这些问题:

showErrors: function (errorMap, errorList) {
        $.each(this.successList, function (index, element) {
            return $(element).popover("destroy");
        });

        $.each(errorList, function (index, error) {
            var ele = $(error.element); //Instead of referencing the popover directly, I use the element that is the target for the popover

            ele.popover({
                    trigger: "manual",
                    placement: "top",
                    content: function(){ //use a function to assign the error message to content
                        return error.message
                    },
                    template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><div class="popover-content"><p></p></div></div></div>'
            });

            //bs.popover must be used, not just popover
            ele.data("bs.popover").options.content = error.message;

            return $(error.element).popover("show");
        });
    }