jQuery 验证必需选择

发布于 2024-09-02 23:49:56 字数 369 浏览 2 评论 0原文

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

UPD。例子。想象一下我们有以下 html 控件:

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

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

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?

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

<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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

染柒℉ 2024-09-09 23:49:56

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

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

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

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>
独守阴晴ぅ圆缺 2024-09-09 23:49:56

您可以编写自己的规则!

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

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!" }
  }  
 });
雅心素梦 2024-09-09 23:49:56

最简单的解决方案

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

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

jquery 验证< /a> 必需规则将起作用

the most simple solution

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

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

and jquery validation required rule will work

一念一轮回 2024-09-09 23:49:56

使用最小规则

将第一个选项值设置为 0

'selectName':{min:1}

use min rule

set first option value to 0

'selectName':{min:1}
北方的巷 2024-09-09 23:49:56

您只需将 validate[required] 作为此选择的类,然后放置一个带有 value="" 的选项,

例如:

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

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

for example:

<select class="validate[required]">
  <option value="">Choose...</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>
流星番茄 2024-09-09 23:49:56

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

  1. 给你的选择标签一个名称属性。例如本例

  2. 不要使用标签选项中的属性 value="default",而是禁用默认选项或设置 value=" “按照安德鲁·科茨的建议

    <选项禁用=“禁用”>选择...

  3. 设置插件验证规则

    $( "#YOUR_FORM_ID" ).validate({
    规则:{
    myselect: { 必需: true }
    }
    });

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

希望有帮助! :)

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:

  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">

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.

Hope it helps! :)

假情假意假温柔 2024-09-09 23:49:56
<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>
<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 $
<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>
<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 $
樱花细雨 2024-09-09 23:49:56
<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>

选择值将为空

<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

惯饮孤独 2024-09-09 23:49:56

@JMP 提到的解决方案适用于我的情况,只需稍加修改即可:
我在 addmethod 中使用 element.value 而不是 value

$.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!" }
    }  
});

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

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

$.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.

街角迷惘 2024-09-09 23:49:56

很简单,您需要获取 Select 字段值,并且它不能是“默认”。

if($('select').val()=='default'){
    alert('Please, choose an option');
    return false;
}

It's simple, you need to get the Select field value and it cannot be "default".

if($('select').val()=='default'){
    alert('Please, choose an option');
    return false;
}
橘虞初梦 2024-09-09 23:49:56

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

$(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;
        }
    });

});

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

$(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;
        }
    });

});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文