如何强制jQuery验证在表单元素内部而不是外部显示错误?
以jqueryvalidate的这个基本示例(参见下面的链接)为例,您如何指示它在可能的情况下显示表单元素中的错误消息(显然复选框不起作用)如何强制jQuery验证在表单元素内部而不是外部显示错误?,jquery,css,jquery-validate,Jquery,Css,Jquery Validate,以jqueryvalidate的这个基本示例(参见下面的链接)为例,您如何指示它在可能的情况下显示表单元素中的错误消息(显然复选框不起作用) 显然,你会想为自己的身体量身定做,但绝对定位可能会对你有所帮助。你举的例子是: [截断]标记: <form class="cmxform" id="commentForm" method="get" action=""> <fieldset> <legend>A simple comment form with
显然,你会想为自己的身体量身定做,但绝对定位可能会对你有所帮助。你举的例子是: [截断]标记:
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>A simple comment form with submit validation and default messages</legend>
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
</p>
</fieldset>
</form>
.cmxform p{position:relative;}
.cmxform label.error{position:absolute; left: 11.7em; top:5px; display:block; width:180px; /*Computed width of text input was 189px*/ overflow:hidden;}
当然,这种方法确实有一个主要缺点,那就是错误标签将挂在用户正在键入的内容之上。在jquery.com的例子中,我在键入名字的第一个字母上有一条红色的“请输入至少2个字符”消息。要解决此问题,您需要执行以下操作:
$(document).ready(function(){
$('.cmxform input[type=text]').focus(function(){
$(this).siblings('.error').hide(); // Hide the error while the user is typing
}).blur(function(){
if( !$('#commentForm').validate().element(this) ){ // Re-validate this element, show the label if still invalid
$(this).siblings('.error').show();
}
});
});