jQuery 验证需要选择

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

jQuery Validate Required Select

jqueryjquery-validate

提问by SiberianGuy

I am trying to validate html select element using jQuery Validate plugin. I set "required" rule to true but it always passes validation because zero index is chosed by default. Is there any way to define empty value that is used by required rule?

我正在尝试使用 jQuery Validate 插件验证 html select 元素。我将“必需”规则设置为 true 但它总是通过验证,因为默认情况下选择了零索引。有没有办法定义所需规则使用的空值?

UPD. Example. Imagine we have the following html control:

更新。例子。假设我们有以下 html 控件:

<select>
  <option value="default">Choose...</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

I want Validation plugin to use "default" value as empty.

我希望验证插件使用“默认”值作为空。

回答by Andrew Coats

An easier solution has been outlined here: Validate select box

这里概述了一个更简单的解决方案: 验证选择框

Make the value be empty and add the required attribute

将该值设为空并添加所需的属性

<select id="select" class="required">
<option value="">Choose an option</option> 
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>

回答by JMP

You can write your own rule!

您可以编写自己的规则!

 // add the rule here
 $.validator.addMethod("valueNotEquals", function(value, element, arg){
  return arg !== value;
 }, "Value must not equal arg.");

 // configure your validation
 $("form").validate({
  rules: {
   SelectName: { valueNotEquals: "default" }
  },
  messages: {
   SelectName: { valueNotEquals: "Please select an item!" }
  }  
 });

回答by Basheer AL-MOMANI

the most simple solution

最简单的解决办法

just set the value of the first option to empty string value=""

只需将第一个选项的值设置为空字符串 value=""

<option value="">Choose...</option>

and jquery validationrequiredrule will work

jquery 验证required规则 will work

回答by Funky Dude

use min rule

使用最小规则

set first option value to 0

将第一个选项值设置为 0

'selectName':{min:1}

回答by omalave

You only need to put validate[required]as class of this select and then put a option with value=""

你只需要把validate[required]这个选择的类放入,然后放入一个 value="" 的选项

for example:

例如:

<select class="validate[required]">
  <option value="">Choose...</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

回答by Pedro Paulo Mendes Pereira

I don't know how was the plugin the time the question was asked (2010), but I faced the same problem today and solved it this way:

我不知道在提出问题时插件如何(2010 年),但我今天遇到了同样的问题并以这种方式解决了它:

  1. Give your select tag a name attribute. For example in this case

    <select name="myselect">

  2. Instead of working with the attribute value="default" in the tag option, disable the default option or set value="" as suggested by Andrew Coats

    <option disabled="disabled">Choose...</option>

    or

    <option value="">Choose...</option>

  3. Set the plugin validation rule

    $( "#YOUR_FORM_ID" ).validate({ rules: { myselect: { required: true } } });

    or

    <select name="myselect" class="required">

  1. 给你的选择标签一个名称属性。例如在这种情况下

    <select name="myselect">

  2. 不要在标签选项中使用属性 value="default",而是按照 Andrew Coats 的建议禁用默认选项或设置 value=""

    <option disabled="disabled">Choose...</option>

    或者

    <option value="">Choose...</option>

  3. 设置插件验证规则

    $( "#YOUR_FORM_ID" ).validate({ rules: { myselect: { required: true } } });

    或者

    <select name="myselect" class="required">

Obs: Andrew Coats' solution works only if you have just one select in your form. If you want his solution to work with more than one select add a name attribute to your select.

Obs:Andrew Coats 的解决方案仅在您的表单中只有一个选择时才有效。如果您希望他的解决方案与多个选择一起使用,请向您的选择添加名称属性。

Hope it helps! :)

希望能帮助到你!:)

回答by fthopkins

Here is the simple and understandable example :

这是一个简单易懂的例子:

   <select class="design" id="sel" name="subject">
        <option value="0">- Please Select -</option>
        <option value="1"> Example1 </option>
        <option value="2"> Example2 </option>
        <option value="3"> Example3 </option>
        <option value="4"> Example4 </option>
   </select>

    <label class="error" id="select_error" style="color:#FC2727"><b> Warning : You have to Select One Item.</b></label><td>

    <input type="submit" name="sub" value="G?nder" class="">

JQuery :

查询:

jQuery(function() {  

jQuery('.error').hide(); // Hide Warning Label. 

jQuery("input[name=sub]").on("click", function() {

   var returnvalue;

   if(jQuery("select[name=subject]").val() == 0) {

        jQuery("label#select_error").show(); // show Warning 
        jQuery("select#sel").focus();  // Focus the select box      
        returnvalue=false;   

}

return returnvalue;

});
      });  // you can change jQuery with $

回答by abhishek kumar

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>

 <form id="myform"> 
       <select class="form-control" name="user_type">
        <option value="">Select</option>
        <option value="2">1</option>
        <option value="3">2</option>
        </select>
       </form>


<script>
  $('#myform').validate({ // initialize the plugin
            rules: {
          user_type:{ required: true},
         }
      });
</script>

select value will be blank

选择值将为空

回答by Legends

The solution mentioned by @JMP worked in my case with a little modification: I use element.valueinstead of valuein the addmethod.

@JMP 提到的解决方案在我的情况下进行了一些修改:我使用element.value而不是valueaddmethod.

$.validator.addMethod("valueNotEquals", function(value, element, arg){
    // I use element.value instead value here, value parameter was always null
    return arg != element.value; 
}, "Value must not equal arg.");

// configure your validation
$("form").validate({
    rules: {
        SelectName: { valueNotEquals: "0" }
    },
    messages: {
        SelectName: { valueNotEquals: "Please select an item!" }
    }  
});

It could be possible, that I have a special case here, but didn't track down the cause. But @JMP's solution should work in regular cases.

有可能,我在这里有一个特殊情况,但没有找到原因。但是@JMP 的解决方案应该适用于常规情况。

回答by michele

how to validate the select "qualifica" it has 3 choose

如何验证它有 3 个选择的选择“qualifica”

$(document).ready(function(){

    $('.validateForm').validate({
        rules: {
            fullname: 'required',
            ragionesociale: 'required',
            partitaiva: 'required',
            recapitotelefonico: 'required',
            qualifica: 'required',
            email: {
                required: true,
                email: true
            },
        },
        submitHandler: function(form) {

            var fullname = $('#fullname').val(),
                            ragionesociale = $('#ragionesociale').val(),
                            partitaiva = $('#partitaiva').val(),
                            email = $('#email').val(),
                            recapitotelefonico = $('#recapitotelefonico').val(),
                            qualifica = $('#qualifica').val(),
                            dataString = 'fullname=' + fullname + '&ragionesociale=' + ragionesociale + '&partitaiva=' + partitaiva + '&email=' + email + '&recapitotelefonico=' + recapitotelefonico + '&qualifica=' + qualifica;

            $.ajax({
                type: "POST",
                url: "util/sender.php",
                data: dataString,
                success: function() {

                    window.location.replace("./thank-you-page.php");


                }
            });
            return false;
        }
    });

});