为什么jquery validate plugin不能验证我的复选框?

时间:2012-03-26 05:43:34

标签: jquery jquery-plugins jquery-validate

此代码是从另一个文件复制的,它在该文件中工作,我检查了变量和表单ID,我确信该名称与js代码一致。 genFrom中的文本框也验证有效,只有复选框无效。

<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script>
$(document).ready(function(){
    $("#genForm").validate();
    $("#genForm").validate( {
        rules: {
            agree: {
                required: true
            }
        }
    })
});
</script>
<form id="genForm"  method="post" action="verify.php">
<div class="container">
    <div class="hero-unit">
        <h1>Subscribe for final</h1>
    </div>
    <div class="clearfix">
        <label>Email</label>
        <div class="input">
            <input name="Email" type="text" class='required'>
        </div>
    </div>
    <br>
    <br>
    <div class="clearfix">
    <label>Agreements:</label>
        <div class="input"> 
        <ul class="inputs-list">
            <li>                                      
            I accept the terms and conditions.
            <!-- Check box is here, not working -->
            <input type="checkbox" name="agree" value="1">
            </li>
        </ul>
        </div> 
    </div> 
    <br>
    <input class="btn primary" type="submit" value="Submit">
</form>

1 个答案:

答案 0 :(得分:4)

由于某种原因,您在同一表单上拨打validate()两次,只需要一个:

// $("#genForm").validate(); No need for this

$("#genForm").validate( {
  rules: {
      agree: {
          required: true
      }
   }
});

演示:http://jsfiddle.net/8MV5F/

调用没有params的validate()确实有一些(可配置的)默认行为,其中一个是将required规则附加到class='required'的元素,这就是电子邮件字段工作的原因。您也可以使用required属性,此外,您可以使用type="email"作为电子邮件地址进行验证,而无需在规则中指定。

以下是一个简单示例:http://jsfiddle.net/8MV5F/2/

<form id="genForm"  method="post" action="verify.php">
    <label>Email:<input name="Email" type="email" required></label>          
    <label>I accept the terms and conditions.
    <input type="checkbox" name="agree" value="1" required></label>
    <input class="btn primary" type="submit" value="Submit">
</form>
$("#genForm").validate();

如果支持,如果支持javascript,甚至只是破坏了,那么这有利于回退到原生浏览器验证。

相关问题