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

时间:2022-03-01 00:10:50

I have some <select> inputs using the chosen plugin that 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).

我有一些

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 select through with an empty value, without validating or showing the error message. When I comment out the chosen() line, it works fine.

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

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

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

14 个解决方案

#1


111  

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

jQuery验证忽略隐藏的元素,并且由于所选的插件增加了可见性:隐藏属性的选择,尝试:

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

.validator美元。setDefaults({忽略:“隐藏:没有(选择)”})/ /选择

OR

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

.validator美元。setDefaults({忽略:“隐藏:没有(.chosen-select)”}) // /对于所有的select have class .chosen-select

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

在validate()函数之前添加这一行。对我来说很好。

#2


18  

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')

#3


4  

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校验的choosen的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'

注意:如果输入值为null,类错误将被追加到父“div”

#4


3  

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

    });
});

#5


1  

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验证实际上添加了一个隐藏的标签html元素。我们可以在不同的位置用相同的ID重新定义这个元素,以覆盖原始位置。

#6


1  

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

这个简单的CSS规则适用于joomla 3的选择实现

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

选择将无效的类添加到隐藏的select输入中,因此使用这个来针对所选的select框

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

#7


1  

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

我得下$.validator。setDefaults({忽略:“隐藏:没有(.chosen-select)”})在$(文档)之外。ready(函数),以便与chosen.js一起工作。

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

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

#8


1  

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

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

Enable .chosen to be considered

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

由于大麻

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 $.validator object. Can be put next to the previous command

同样,$的全局配置。验证器对象。可以放在前面的命令旁边吗

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

#9


0  

jQuery("#formID").validationEngine({
     prettySelect : true,
     useSuffix: "_chzn"
});

jQuery-Validation-Engine/demoChosenLibrary

jQuery-Validation-Engine / demoChosenLibrary

#10


0  

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-chosen class on each selects.

记住在每个选择项上添加.select类。

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

$('. selectchosen ').valid()强制对隐藏的选择进行验证。

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

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

#11


0  

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 validationEngine 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"
});

#12


0  

My form includes conditionally hidden fields, to prevent the hidden chosen fields failing validation I've extended the default ignore:hidden a little further:

我的表单包含有条件的隐藏字段,以防止隐藏选择的字段失败验证。

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

#13


0  

I think this is the better solution.

我认为这是更好的解决办法。

//trigger validation onchange
$('select').on('change', function() {
    $(this).valid();
});

$('form').validate({
    ignore: ':hidden', //still ignore Chosen selects
    submitHandler: function(form) { //all the fields except Chosen selects have already passed validation, so we manually validate the Chosen selects here            
        var $selects = $(form).find('select'),
            valid = true;
        if ($selects.length) {
            //validate selects
            $selects.each(function() {
                if (!$(this).valid()) {
                    valid = false;
                }
            });
        }
        //only submit the form if all fields have passed validation
        if (valid) {
            form.submit();
        }
    },
    invalidHandler: function(event, validator) { //one or more fields have failed validation, but the Chosen selects have not been validated yet
        var $selects = $(this).find('select');     
        if ($selects.length) {
            validator.showErrors(); //when manually validating elements, all the errors in the non-select fields disappear for some reason

            //validate selects
            $selects.each(function(index){
                validator.element(this);
            })
         }
    },
    //other options...
});

Note: You will also need to change the errorPlacement callback to handle displaying the error. If your error message is next to the field, you will need to use .siblings('.errorMessageClassHere') (or other ways depending on the DOM) instead of .next('.errorMessageClassHere').

注意:您还需要更改errorPlacement回调来处理显示错误。如果您的错误消息在字段旁边,您将需要使用.sibling ('. errormessageclasshere ')(或者根据DOM的其他方式)而不是.next('. errormessageclasshere ')。

#14


0  

In the year 2018 I am verifying that jQuery validate is complaining about an input field with no name. This input field is appended by the jQuery Chosen plguin.

在2018年,我正在验证jQuery validate正在抱怨一个没有名称的输入字段。这个输入字段由jQuery选择的plguin附加。

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

This bug is happening before anything else when using chosen.

在使用选择时,这个错误发生在任何事情之前。

#1


111  

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

jQuery验证忽略隐藏的元素,并且由于所选的插件增加了可见性:隐藏属性的选择,尝试:

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

.validator美元。setDefaults({忽略:“隐藏:没有(选择)”})/ /选择

OR

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

.validator美元。setDefaults({忽略:“隐藏:没有(.chosen-select)”}) // /对于所有的select have class .chosen-select

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

在validate()函数之前添加这一行。对我来说很好。

#2


18  

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')

#3


4  

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校验的choosen的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'

注意:如果输入值为null,类错误将被追加到父“div”

#4


3  

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

    });
});

#5


1  

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验证实际上添加了一个隐藏的标签html元素。我们可以在不同的位置用相同的ID重新定义这个元素,以覆盖原始位置。

#6


1  

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

这个简单的CSS规则适用于joomla 3的选择实现

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

选择将无效的类添加到隐藏的select输入中,因此使用这个来针对所选的select框

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

#7


1  

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

我得下$.validator。setDefaults({忽略:“隐藏:没有(.chosen-select)”})在$(文档)之外。ready(函数),以便与chosen.js一起工作。

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

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

#8


1  

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

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

Enable .chosen to be considered

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

由于大麻

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 $.validator object. Can be put next to the previous command

同样,$的全局配置。验证器对象。可以放在前面的命令旁边吗

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

#9


0  

jQuery("#formID").validationEngine({
     prettySelect : true,
     useSuffix: "_chzn"
});

jQuery-Validation-Engine/demoChosenLibrary

jQuery-Validation-Engine / demoChosenLibrary

#10


0  

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-chosen class on each selects.

记住在每个选择项上添加.select类。

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

$('. selectchosen ').valid()强制对隐藏的选择进行验证。

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

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

#11


0  

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 validationEngine 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"
});

#12


0  

My form includes conditionally hidden fields, to prevent the hidden chosen fields failing validation I've extended the default ignore:hidden a little further:

我的表单包含有条件的隐藏字段,以防止隐藏选择的字段失败验证。

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

#13


0  

I think this is the better solution.

我认为这是更好的解决办法。

//trigger validation onchange
$('select').on('change', function() {
    $(this).valid();
});

$('form').validate({
    ignore: ':hidden', //still ignore Chosen selects
    submitHandler: function(form) { //all the fields except Chosen selects have already passed validation, so we manually validate the Chosen selects here            
        var $selects = $(form).find('select'),
            valid = true;
        if ($selects.length) {
            //validate selects
            $selects.each(function() {
                if (!$(this).valid()) {
                    valid = false;
                }
            });
        }
        //only submit the form if all fields have passed validation
        if (valid) {
            form.submit();
        }
    },
    invalidHandler: function(event, validator) { //one or more fields have failed validation, but the Chosen selects have not been validated yet
        var $selects = $(this).find('select');     
        if ($selects.length) {
            validator.showErrors(); //when manually validating elements, all the errors in the non-select fields disappear for some reason

            //validate selects
            $selects.each(function(index){
                validator.element(this);
            })
         }
    },
    //other options...
});

Note: You will also need to change the errorPlacement callback to handle displaying the error. If your error message is next to the field, you will need to use .siblings('.errorMessageClassHere') (or other ways depending on the DOM) instead of .next('.errorMessageClassHere').

注意:您还需要更改errorPlacement回调来处理显示错误。如果您的错误消息在字段旁边,您将需要使用.sibling ('. errormessageclasshere ')(或者根据DOM的其他方式)而不是.next('. errormessageclasshere ')。

#14


0  

In the year 2018 I am verifying that jQuery validate is complaining about an input field with no name. This input field is appended by the jQuery Chosen plguin.

在2018年,我正在验证jQuery validate正在抱怨一个没有名称的输入字段。这个输入字段由jQuery选择的plguin附加。

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

This bug is happening before anything else when using chosen.

在使用选择时,这个错误发生在任何事情之前。