如何在“选择”插件中使用 jQuery 验证?

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

How can I use jQuery validation with the "chosen" plugin?

jqueryjquery-validatejquery-chosen

提问by Wesley Murch

I have some <select>inputs using the chosen pluginthat I want to validate as "required" on the client side. Since "chosen" hides the actual select element and creates a widget with divs and spans, native HTML5 validation doesn't seem to work properly. The form won't submit (which is good), but the error message is not shown, so the user has no idea what's wrong (which is not good).

我有一些<select>使用所选插件的输入,我想在客户端验证为“必需”。由于“选择”隐藏了实际的 select 元素并创建了一个带有 div 和 span 的小部件,因此原生 HTML5 验证似乎无法正常工作。表单不会提交(这很好),但没有显示错误消息,因此用户不知道出了什么问题(这不好)。

I've turned to the jQuery validation plugin (which I planned on using eventually anyways) but haven't had any luck so far. Here's my test case:

我已经转向了 jQuery 验证插件(我计划最终使用它)但到目前为止还没有任何运气。这是我的测试用例

<form>
    <label>Name: <input name="test1" required></label>
    <label>Favorite Color:
        <select name="test2" required>
            <option value=""></option>
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="green">Green</option>
        </select>
    </label>
    <input type="submit">
</form>
$(document).ready(function(){
    $('select').chosen();
    $('form').validate();
});

This is letting the selectthrough with an empty value, without validating or showing the error message. When I comment out the chosen()line, it works fine.

这是让select一个空值通过,而不验证或显示错误消息。当我注释掉该chosen()行时,它工作正常。

How can I validate chosen()inputs with the jQuery validation plugin, and show the error message for invalid ones?

如何chosen()使用 jQuery 验证插件验证输入,并显示无效输入的错误消息?

回答by Anupal

jQuery validate ignores the hidden element, and since the Chosen plugin adds visibility:hiddenattribute to the select, try:

jQuery validate 忽略隐藏元素,并且由于 Chosen 插件为选择添加了visibility:hidden属性,请尝试:

$.validator.setDefaults({ ignore: ":hidden:not(select)" }) //for all select

$.validator.setDefaults({ ignore: ":hidden:not(select)" }) //for all select

OR

或者

$.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" }) //for all select having class .chosen-select

$.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" }) //for all select having class .chosen-select

Add this line just before validate()function. It works fine for me.

validate()函数之前添加这一行。这对我来说可以。

回答by Mike Robinson

jQuery validation isn't going to pick up elements that are hidden, but you can force it to validate individual elements. Bit of a hack, but the following will work:

jQuery 验证不会选取隐藏的元素,但您可以强制它验证单个元素。有点黑客,但以下将起作用:

$('form').on('submit', function(e) {
    if(!$('[name="test2"]').valid()) {
        e.preventDefault();
    }
});  

To select only "chosen" elements you can use $('.chzn-done')

要仅选择您可以使用的“选定”元素 $('.chzn-done')

回答by Acang Terpal

in mine.

在我的。

my form has class 'validate' and every input element has class 'required' html code:

我的表单有“validate”类,每个输入元素都有“required”类的html代码:

<form id="ProdukProdukTambahForm" class="validate form-horizontal" accept-charset="utf-8" method="post" enctype="multipart/form-data" action="/produk-review/produk/produkTambah" novalidate="novalidate">
     <div class="control-group">
        <label class="control-label" for="sku">SKU</label>
        <div class="controls">
           <input id="sku" class="required span6" type="text" name="sku">
        </div>
     </div>
     <div class="control-group">
        <label for="supplier" class="control-label">Supplier</label>
        <div class="controls">
            <select name="supplier" id="supplier" class='cho span6 {required:true} '>                                           
                <option value=''>-- PILIH --</option>
                <?php
                foreach ($result as $res)
                    {
                    echo '<option value="'.$res['tbl_suppliers']['kode_supplier'].'">'.$res['tbl_suppliers']['nama_supplier'].'</option>';
                    }
                ?>
            </select>
         </div>
      </div>
</form>

and javascript code for choosen with jquery validation

和使用 jquery 验证选择的 javascript 代码

$(document).ready(function() {
    // - validation
    if($('.validate').length > 0){
        $('.validate').validate({
            errorPlacement:function(error, element){
                    element.parents('.controls').append(error);
            },
            highlight: function(label) {
                $(label).closest('.control-group').removeClass('error success').addClass('error');
            },
            success: function(label) {
                label.addClass('valid').closest('.control-group').removeClass('error success').addClass('success');
            },
            //validate choosen select (select with search)
            ignore: ":hidden:not(select)"
        });
    }
    // - chosen, add the text if no result matched
    if($('.cho').length > 0){
        $(".cho").chosen({no_results_text: "No results matched"});
    }
});

note: if the input value is null, the class error will be append to parent 'div'

注意:如果输入值为空,类错误将附加到父'div'

回答by vikrant singh

//You can fix this by using another way to hide your chosen element. eg....

//您可以通过使用另一种方式隐藏您选择的元素来解决此问题。例如....

$(document).ready(function() {
 $.validator.addMethod(     //adding a method to validate select box//
            "chosen",
            function(value, element) {
                return (value == null ? false : (value.length == 0 ? false : true))
            },
            "please select an option"//custom message
            );

    $("form").validate({
        rules: {
            test2: {
                chosen: true
            }
        }
    });
    $("[name='test2']").css("position", "absolute").css("z-index",   "-9999").chosen().show();

    //validation.....
    $("form").submit(function()
    {
        if ($(this).valid())
        {alert("valid");
    //some code here 
        }
        return false;

    });
});

回答by Tobi G.

I had to place $.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" })
outside $(document).ready(function())in order to work with chosen.js.

我不得不放在$.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" })
外面$(document).ready(function())才能使用 selected.js。

https://stackoverflow.com/a/10063394/4063622

https://stackoverflow.com/a/10063394/4063622

回答by philip

this simple CSS rule works on joomla 3's implementation of chosen

这个简单的 CSS 规则适用于 joomla 3 的 selected

Chosen adds the class invalid to the hidden select input so use this to target the chosen select box

选择将类 invalid 添加到隐藏的选择输入中,因此使用它来定位选定的选择框

.invalid, .invalid + div.chzn-container a {
    border-color: red !important;
}

回答by Alwin Kesler

@Anupal put me on the right path but somehow I needed a complex fix

@Anupal 让我走上了正确的道路,但不知何故我需要一个复杂的修复

Enable .chosento be considered

启用.chosen被考虑

javascript

javascript

$.validator.setDefaults({ ignore: ":hidden:not(.chosen)" })

Or any other name you give to your chosen's. This is global configuration. Consider setting on top level

或者你给你选择的任何其他名字。这是全局配置。考虑在顶层设置

Create custom rule for chosen

为选择的创建自定义规则

Thanks to BenG

感谢BenG

html

html

<select id="field" name="field" class="chosen" data-rule-chosen-required="true">
    <option value="">Please select…</option>
</select>

javascript

javascript

Again, global configuration for $.validatorobject. Can be put next to the previous command

再次,$.validator对象的全局配置。可以放在上一个命令旁边

$.validator.addMethod('chosen-required', function (value, element, requiredValue) {
    return requiredValue == false || element.value != '';
}, $.validator.messages.required);

回答by Gavin Tian

You might also running into trouble that error message is displayed before Chosen dropdownlist. I found out the solution to resolve this issue and paste my code here to share with you

您可能还会遇到在选择下拉列表之前显示错误消息的问题。我找到了解决此问题的解决方案并将我的代码粘贴到此处与您分享

HTML:

HTML:

<label class="col-sm-3">Select sponsor level *</label>
<asp:DropDownList ID="ddlSponsorLevel" runat="server" CssClass="col-sm-4 required" ClientIDmode="Static" />
<label class="error" id="ddlSponsorLevel-error" for="ddlSponsorLevel"></label>

Javascript:

Javascript:

if (!$('#ddlSponsorLevel').valid()) {
       $('#ddlSponsorLevel-error').text("You must choose a sponsor level");
            return false;
}

Jquery Validation actually added a hidden label html element. We can re-define this element with same ID on different place to overwrite original place.

Jquery Validation 实际上添加了一个隐藏的标签 html 元素。我们可以在不同的地方重新定义这个具有相同 ID 的元素来覆盖原来的地方。

回答by Mav2287

I spent about a day working on this and had no luck at all! Then I looked at the source code Vtiger was using and found gold! Even though they were using older versions they had the key! you have to use

我花了大约一天的时间来研究这个,但一点运气都没有!然后我查看了 Vtiger 使用的源代码,发现了金子!即使他们使用的是旧版本,他们也有钥匙!你必须使用

data-validation-engine="validate[required]"

If you don't and you have it where classes are passed through the class for the select gets applied to the chosen and it thinks that your chosen never gets updated. If you don't pass the class onto the chosen this should be a problem, BUT if you do this is the only way it will work.

如果您不这样做,并且您在类通过类传递的情况下将选择应用于所选对象,并且它认为您选择的对象永远不会更新。如果您没有将课程传递给所选课程,这应该是一个问题,但如果您这样做,这是唯一可行的方法。

This is with chosen 1.4.2 validationEngine 2.6.2 and jquery 2.1.4

这是选择 1.4.2 验证引擎 2.6.2 和 jquery 2.1.4

// binds form submission and fields to the validation engine
jQuery("#FORMNAME").validationEngine({
    prettySelect : true,
    useSuffix: "_chosen"
    //promptPosition : "bottomLeft"
});

回答by Fred K

You can also try this:

你也可以试试这个:

$('form').on('submit', function(event) {
    event.preventDefault();
    if($('form').valid() == true && $('.select-chosen').valid() == true){
        console.log("Valid form");
    } else {
        console.log("Invalid form");
    }
}); 

Remember to add .select-chosenclass on each selects.

请记住.select-chosen在每个selects上添加类。

$('.select-chosen').valid()forces the validation for the hidden selects

$('.select-chosen').valid()强制验证隐藏的selects

http://jsfiddle.net/mrZF5/39/

http://jsfiddle.net/mrZF5/39/