gpt4 book ai didi

jQuery 验证仍然提交无效字段

转载 作者:搜寻专家 更新时间:2023-10-31 23:10:19 25 4
gpt4 key购买 nike

我正在使用 jQuery 验证,但遇到了两个问题。第一,下拉列表 selection 不验证,并且 (2) 如果字段无效,它仍然提交。 (我也在用bootstrap)

我的 html:

<form action="" id="contact-form" class="form-horizontal">
<fieldset>
<legend>Contact Us</small>
</legend>
<div class="control-group">
<label class="control-label" for="name">Name:</label>
<div class="controls">
<input type="text" class="input-xlarge" name="name" id="name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">Email Address:</label>
<div class="controls">
<input type="text" class="input-xlarge" name="email" id="email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="subject">Subject:</label>
<div class="controls">
<select name="subject" id="subject">
<option value></option>
<option value- "1">General Questions</option>
<option value- "2">Membership</option>
<option value- "3">Club Fees</option>
<option value- "4">Proshop & Lessons</option>
<option value- "5">Events</option>
<option value- "6">Leagues &amp; Programs</option>
<option value- "7">Resturant &amp; Bar</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="message">Message:</label>
<div class="controls">
<textarea class="input-xlarge" name="message" id="message" rows="3"></textarea>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Submit</button>
<button class="btn">Cancel</button>
</div>
</fieldset>
</form>

我的 JavaScript:

$(document).ready(function() {
$('#contact-form').validate({
rules: {
name: {
minlength: 2,
maxlength: 20,
required: true
},
email: {
required: true,
email: true
},
subject: {
selectNone: true

},
message: {
minlength: 2,
required: true
}
},
highlight: function(label) {
$(label).closest('.control-group').addClass('error');
},
success: function(label) {
label
.text('OK!').addClass('valid')
.closest('.control-group').addClass('success');
}
});

问题:

  1. 为什么下拉菜单无效?
  2. 为什么表单未经验证就提交?

最佳答案

首先,你所有的value="0"在你的<option>标签实际上是 value-0 - 需要更正。

对于表单提交的问题,你需要在你的提交操作上阻止默认操作,并添加一个 submitHandler 操作来成功:

$(document).ready(function(){
$('#contact-form').submit(function(e){
e.preventDefault();
}).validate({
rules: {
name: {
minlength: 2,
maxlength: 20,
required: true
},
email: {
required: true,
email: true
},
subject: {
selectNone: true

},
message: {
minlength: 2,
required: true
}
},
highlight: function(label) {
$(label).closest('.control-group').addClass('error');
},
success: function(label) {
label
.text('OK!').addClass('valid')
.closest('.control-group').addClass('success');
},
submitHandler: function(form){
form.submit();
}
});

关于jQuery 验证仍然提交无效字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10360663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com