ASP.Net MVC验证不适用于Bootstrap Select Picker

时间:2014-09-29 16:08:45

标签: asp.net-mvc twitter-bootstrap

我发现ASP.NET MVC验证没有使用Bootstrap Select Picker,如果我从下拉列表中删除selectpicker类,验证工作正常,如果我添加验证不起作用,请帮助

MVC代码:

 @Html.DropDownListFor(m => m.SelectedLocationID, Model.lstOfLocations, "Select Delivery Location", new { @class = " selectpicker", @placeholder = "" })
            @Html.ValidationMessageFor(m => m.SelectedLocationID)

使用Valida-min.js的Jquery代码

 $(".SearchForm").validate({
        ignore: ':not(select:hidden, input:visible, textarea:visible)',
        rules: {
            SelectedLocationID: {
                required: true
            }
        },
        errorPlacement: function (error, element) {
            if ($(element).is('Select Delivery Location')) {
                element.next().after(error);
            } else {
                error.insertAfter(element);
            }
        }
    })

由于

3 个答案:

答案 0 :(得分:3)

我在寻找相同问题的修复时偶然发现了这个问题。

问题来自于事实,Bootstrap隐藏原始选择元素并创建它自己的元素来处理下拉列表的UI。与此同时,jQuery验证默认忽略不可见的字段。

我通过结合changing validation ignore listfinding parent form的解决方法修复此问题。我案例中的最终代码段如下所示



        if ($(".selectpicker")[0]) {
            $(".selectpicker").selectpicker();
            $('.selectpicker').parents('form:first').validate().settings.ignore = ':not(select:hidden, input:visible, textarea:visible)';
        }




仍然可能存在潜在问题,但根据我的需要,此解决方案的效果非常好。

答案 1 :(得分:0)

问题是由bootstrap select skin给出原始select的display:none属性引起的(jQuery validate忽略隐藏字段)。 可以避免只使用CSS保持原始选择可见,但为其提供一些属性以避免可见性

select.bs-select-hidden, select.selectpicker 
{
    display:block !important; opacity:0; height:1px; width:1px;
}

答案 2 :(得分:-1)

我想,编辑bootstrap-select.js可以永久解决这个问题。 我尝试过这样的事情:

$(document)
        .data('keycount', 0)
        .on('keydown.bs.select', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="listbox"], .bs-searchbox input', Selectpicker.prototype.keydown)
        .on('focusin.modal', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="listbox"], .bs-searchbox input', function (e) {
            //Validation handler: Kartik
            var $thisParent = $(this).parent(".bootstrap-select");
            if ($thisParent.find("ul").find("li:first").hasClass("selected")) {
                if ($thisParent.next("span").length > 0)
                    $thisParent.next("span").css("display", "block");
            }
            else {
                if ($thisParent.next("span").length > 0)
                    $thisParent.next("span").css("display", "none");
            }
            e.stopPropagation();
        });

它对我来说很好。