twitter-bootstrap jQuery Validate 不适用于 Bootstrap 3 选项卡式表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20562229/
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-10-21 19:28:19  来源:igfitidea点击:

jQuery Validate not working on Bootstrap 3 tabbed form

javascriptjquerytwitter-bootstraptabsjquery-validate

提问by Renier

I have looked at this question/answer, and many more like it, but I still cant get my form validation to switch tabs or move to the tab with the error.

我看过这个问题/答案,还有更多类似的问题,但我仍然无法通过表单验证来切换选项卡或移动到有错误的选项卡。

Relevant jQuery:

相关的jQuery:

$(document).ready(function () {

$("form[name=modify]").validate({
    ignore: [],
    rules: {
        first_name: {
            required: true,
        },
        surname: {
            required: true
        },
        id_number: {
            required: true
        },
        mobile_number: {
            number: true,
            minlength: 10,
        },
        home_number: {
            number: true,
            minlength: 10,
        },
        other_contact: {
            number: true,
            minlength: 10,
        },
        line1: {
            required: true,
        },
        city_town: {
            required: true,
        },
        postal_code: {
            required: true,
            minlength: 4,
        },
        curr_renumeration: {
            required: true,
            number: true,
        },
        expect_renumeration: {
            required: true,
            number: true
        },
        email: {
            email: true,
            required: true,
        },
        highlight: function (label) {
            $(label).closest('.control-group').addClass('has-error');
            console.log($(label).closest('.control-group').addClass('has-error'));
            if ($(".tab-content").find("div.tab-pane.active:has(div.has-error)").length == 0) {
                $(".tab-content").find("div.tab-pane:hidden:has(div.has-error)").each(function (index, tab) {
                    var id = $(tab).attr("id");

                    $('a[href="#' + id + '"]').tab('show');
                });
                $('#myTab').on('shown', function (e) {
                    console.log(this);
                    e.target // activated tab
                    $($(e.target).attr('href')).find("div.has-error :input:first").focus();
                });
            }
        },
    }
});
$("[type=submit]").submit(function (e) {
    e.preventDefault();

});

});

You can view it here

你可以在这里查看

What am I missing?

我错过了什么?

Can someone please help me? I cant get it to work.

有人可以帮帮我吗?我无法让它工作。

UPDATE:

更新:

Okay so I have moved some code around and played a bit:

好的,所以我移动了一些代码并进行了一些操作:

$("form[name=modify]").validate({
        highlight : function(label) {
            $(label).closest('.form-group').addClass('has-error');
            $(".tab-content").find("fieldset.tab-pane:has(has-error)").each(function(index, tab) {
                alert("error from if");
                if ($(".tab-content").find("field.tab-pane.active:has(has-error)").length == 0) {
                    alert("error from each");
                    var id = $(tab).attr("id");
                    console.log(id);
                    $('a[href="#' + id + '"]').tab('show');
                }

            });
        },
        invalidHandler : function(event, validator) {
            // 'this' refers to the form
            $('#myTab').on('shown', function(e) {
                console.log(this);
                e.target;// activated tab
                $($(e.target).attr('href')).find("fieldset.has-error :input:first").focus();
            });
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = errors == 1 ? 'You missed 1 field. It has been highlighted' : 'You missed ' + errors + ' fields. They have been highlighted';
                $("div.has-error span").html(message);
                $("div.has-error").show();
            } else {
                $("div.has-error").hide();
            }
        },
        ignore : [],
        rules : {
            first_name : {
                required : true,
            },
            surname : {
                required : true
            },
            id_number : {
                required : true
            },
            mobile_number : {
                number : true,
                minlength : 10,
            },
            home_number : {
                number : true,
                minlength : 10,
            },
            other_contact : {
                number : true,
                minlength : 10,
            },
            line1 : {
                required : true,
            },
            city_town : {
                required : true,
            },
            postal_code : {
                required : true,
                minlength : 4,
            },
            curr_renumeration : {
                required : true,
                number : true,
            },
            expect_renumeration : {
                required : true,
                number : true
            },
            email : {
                email : true,
                required : true,
            },

        }
    });

All works well, except it stops at this line if ($(".tab-content").find("field.tab-pane.active:has(has-error)").length == 0) {

一切正常,除了它停在这条线上 if ($(".tab-content").find("field.tab-pane.active:has(has-error)").length == 0) {

and if I swop it with $(".tab-content").find("fieldset.tab-pane:has(has-error)").each(function(index, tab) {it stop as well...

如果我用$(".tab-content").find("fieldset.tab-pane:has(has-error)").each(function(index, tab) {它交换它也停止......

Updated jsFiddle

更新了jsFiddle

Why does it not go into the .eachor thif?

为什么它不进入.eachor th if

采纳答案by Renier

So...

所以...

I have solved my problem...

我已经解决了我的问题...

I had to adjust this answera bit.

我不得不稍微调整一下这个答案

My solution was:

我的解决方案是:

  • Inside my $("form[name=modify]").validate({})I called a function named highlight,

  • Instead of using $(".tab-content"), I used the paramater labelto create a variable:

    var tab_content=$(label).parent().parent().parent().parent().parent().parent().parent();
    
  • Maybe not the most efficient way nor the best way to do it... but it works..

  • I also removed :hiddenfrom this line:

    $(".tab-content").find("div.tab-pane:hidden:has(div.has-error)").each(function(index, tab)
    
  • 在我的内部,我$("form[name=modify]").validate({})调用了一个名为 的函数highlight

  • $(".tab-content")我没有使用,而是使用参数label来创建一个变量:

    var tab_content=$(label).parent().parent().parent().parent().parent().parent().parent();
    
  • 也许不是最有效的方法,也不是最好的方法……但它确实有效……

  • 我也:hidden从这一行中删除:

    $(".tab-content").find("div.tab-pane:hidden:has(div.has-error)").each(function(index, tab)
    

Here is the complete function:

这是完整的功能:

        $("form[name=modify]").validate({
        highlight : function(label) {
            $(label).closest('.form-group').addClass('has-error');
            var tab_content= $(label).parent().parent().parent().parent().parent().parent().parent();
            if ($(tab_content).find("fieldset.tab-pane.active:has(div.has-error)").length == 0) {                   
                 $(tab_content).find("fieldset.tab-pane:has(div.has-error)").each(function (index, tab) {
                    var id = $(tab).attr("id");
                $('a[href="#' + id + '"]').tab('show');
                 });
             }
          },
            ignore : [], // <-- this is important
            rules : {
                first_name : {
                    required : true,
                },
                surname : {
                    required : true
                },
                id_number : {
                    required : true
                },
                mobile_number : {
                    number : true,
                    minlength : 10,
                },
                home_number : {
                    number : true,
                    minlength : 10,
                },
                other_contact : {
                    number : true,
                    minlength : 10,
                },
                line1 : {
                    required : true,
                },
                city_town : {
                    required : true,
                },
                postal_code : {
                    required : true,
                    minlength : 4,
                },
                curr_renumeration : {
                    required : true,
                    number : true,
                },
                expect_renumeration : {
                    required : true,
                    number : true
                },
                email : {
                    email : true,
                    required : true,
                },

            }
        });

Check it out on JSFIDDLE

JSFIDDLE查看

  • Note:You do not need the extra function to swap tabs as stated in the answer mentioned above:

    // Don't need this 
    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e){
        e.target // activated tab
    
        $($(e.target).attr('href')).find("div.has-error :input:first").focus();
    
        //e.relatedTarget // previous tab
    }); 
    
  • 注意:您不需要额外的功能来交换上面提到的答案中所述的选项卡:

    // Don't need this 
    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e){
        e.target // activated tab
    
        $($(e.target).attr('href')).find("div.has-error :input:first").focus();
    
        //e.relatedTarget // previous tab
    }); 
    

I do not know why, but you do not need it... Mine works without it anyway...

我不知道为什么,但你不需要它......无论如何我的工作没有它......

I hope this can help someone.

我希望这可以帮助某人。

回答by Chintan Hingrajiya

I think your trouble might be that jquery by default will only validate visible fields. So what you need to do is tell jquery to not ignore your hidden fields (other tabs). This can be done as follows.

我认为您的问题可能是默认情况下 jquery 只会验证可见字段。所以你需要做的是告诉 jquery 不要忽略你的隐藏字段(其他选项卡)。这可以按如下方式完成。

$("#form1").validate({ ignore: "" });

By default, ignore :hidden. See this answer, and this documentation (Options -> Ignore).

默认情况下,忽略:hidden. 请参阅此答案和此文档(选项 -> 忽略)。

回答by Skorunka Franti?ek

$("form").on('submit', function () {
    var isValid = $(this).valid();
    if (this.hasChildNodes('.nav.nav-tabs')) {
        var validator = $(this).validate();
        $(this).find("input").each(function () {
            if (!validator.element(this)) {
                isValid = false;
                $('a[href=#' + $(this).closest('.tab-pane:not(.active)').attr('id') + ']').tab('show');
                return false;
            }
        });
    }
    if (isValid) {
        // do stuff
    }
});