我有一个包含其他子表单(包含为div)的表单,例如:
<form method="post" action="/process" id="form">
<div id="initForm">
<input type="text" name="name" placeholder="Please enter your name" />
<input type="email" name="email" placeholder="Please enter your email" />
<button class="next">Continue</button>
</div>
<div class="subForm">
<input type="text" name="jobPosition" placeholder="Please enter your job position" />
<input type="text" name="jobCompany" placeholder="Please enter your company" />
<button class="next">Continue</button>
</div>
<input type="submit" name="submit" value="Send" />
</form>
我想对表单使用validate
插件,因此每当有人按下next
我想验证此表单的这个特定部分时,它会在允许您继续之前进行验证。因此,我想知道这可能做到这一点吗?我使用了下面的内容,但这没有做任何事情。它没有错误,也没有验证表格。谁能告诉我哪里出错了?
$("form#initForm").validate({
rules: {
name: "required",
},
messages: {
name: "Please enter a valid name"
}
});
答案 0 :(得分:1)
form
的ID与您在jQuery中使用的ID不同,$('form#form")
应该是$('form#form')
或$("form#form")
。
请参阅下面的工作代码:
$(document).ready(function() {
$('#form').validate({
rules: {
name: "required",
jobPosition: "required"
},
messages: {
name: "Please enter a valid name",
jobPosition: "Please enter a valid job"
}
});
$('.next').on('click', function(e){
e.preventDefault();
$(this).parent().find('input:first').valid();
});
});
&#13;
label.error{
color: #F00;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form method="post" action="" id="form">
<div id="initForm">
<input type="text" name="name" placeholder="Please enter your name" />
<input type="email" name="email" placeholder="Please enter your email" />
<button class="next">Continue</button>
</div>
<div class="subForm">
<input type="text" name="jobPosition" placeholder="Please enter your job position" />
<input type="text" name="jobCompany" placeholder="Please enter your company" />
<button class="next">Continue</button>
</div>
<input type="submit" name="submit" value="Send" />
</form>
&#13;