好的,我正在使用jQuery验证插件来检查简单表单上的错误。除错误放置外,一切正常。我试图在包含错误的INPUT之后将我的错误消息放入SPAN元素。出于某种原因,下面的代码将错误消息放在似乎是一个全新的LABEL元素中。知道我在这里做错了吗?
我的HTML
<form action="" id="contact" method="POST">
<p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" class="text proper"/><span class="errMsg"></span>
</p>
<p>
<label for="email">* Email:</label>
<input type="text" name="email" id="email" class="required email text"/><span class="errMsg"></span>
</p>
<p>
<label for="extra">*Question:</label>
<textarea name="onlyText" id="onlyText" class=""></textarea><span class="errMsg"></span>
</p>
<button type="submit" id="send">Send Now</button>
<div id="results"></div>
</form>
我的jQuery
<script>
jQuery(document).ready(function($){
$.validator.addMethod("regex",function(value, element, regexp) {
var check = false;
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"No special Characters allowed here. Use only upper and lowercase letters (A through Z; a through z), numbers and punctuation marks (. , ; ? ' ' \" - ~ ! @ $ % ^ & * ( ) _ + / < > { } )"
);
$("#contact").validate({
rules: {
onlyText:{
required: true,
maxlength: 8000,
regex: /^[0-9A-Za-z\s`~!@$%^&*()+{}|;'",.<>\/?\\-]+$/
},
name:{
required: false,
maxlength: 75,
regex: /^[0-9A-Za-z\s`~!@$%^&*()+{}|;'",.<>\/?\\-]+$/
}
} ,
errorPlacement: function(error, element) {
error.appendTo( element.next() ); //* THIS IS WHERE I AM HAVING TROUBLE WITH
});
});
</script>
答案 0 :(得分:8)
您可以避免麻烦并使用errorElement
和errorClass
选项让插件为您添加正确的元素:
$("#contact").validate({
errorElement: 'span',
errorClass: 'errMsg',
rules: {
onlyText:{
required: true,
maxlength: 8000,
regex: /^[0-9A-Za-z\s`~!@$%^&*()+{}|;'",.<>\/?\\-]+$/
},
name:{
required: false,
maxlength: 75,
regex: /^[0-9A-Za-z\s`~!@$%^&*()+{}|;'",.<>\/?\\-]+$/
}
}
});
答案 1 :(得分:6)
jQuery Validation插件(link to validate())为您提供了指定要用于错误消息的标记的选项:
errorElement: "span"
如果不指定此选项,validate()
将默认为label
。