我有一个正在处理的表单,我的验证JavaScript(jQuery和jQuery验证插件)可以正常工作。我已经设置了一个jsfiddle来显示它的工作状态:http://jsfiddle.net/5Ukv2/
但是,当我使用errorPlacement函数/参数时,它会中断。错误发生在我指定的位置,但是每次更新输入时都会添加多个错误(即任何击键),并且当条目根据JavaScript有效时,错误不会从我的HTML中删除:{{3 }}
此外,只要输入输入字段,验证就会开始;与额外和未删除的错误元素相比,该问题较小。
我做错了什么?
下面附带的代码供参考和在jsfiddles中使用。我评论了几种方法,因为它们正在进行ajax调用,这些调用在这里不起作用,但验证行为相同。
HTML:
<form action="email_submit.php" method="post" name="enterForm" id="enterForm"> <label for="email">Enter your email to play: <input type="text" name="email" id="email" value="" /> <input type="submit" value="Enter" name="submit" class="submit" /> </form>
JavaScript的:
// JavaScript Document
$(function(){
$("#enterForm").validate({
rules: {
email: {
email: true,
required: true,
remote: {url:"email_valid.php", async:false}
}
},
messages:{
email:{
email: "Please enter a valid email address",
required: "Please enter an email address",
remote: "That is not a valid domain"
}
},
submitHandler: function(form) {
var formData = $('form').serialize();
$.ajax({
type: 'POST',
url: "email_submit.php",
data: formData,
success: function(data){
if(data.subscriber && data.valid_email)
window.location = "calendar.html";
else if( !data.valid_email)
alert("Please enter a valid email");
else if( !data.subscriber)
alert("Open sign up form");
},
error: function(data){
alert("e:" + data);
console.log(data);
},
dataType: "JSON"
});
return false;
},
errorPlacement: function (error, element){
if( element.attr("name") == "email" ){
error.insertAfter("#enterForm");
}
else
error.insertAfter(element);
}
});
});
答案 0 :(得分:2)
看起来验证器插件期望将错误放在表单元素中的某个位置。当它正在寻找要隐藏或显示的“错误”元素时,它必须将搜索限制为当前表单。这允许您在页面上有多个表单,并且一个表单中的更改不会影响其他表单。
可以说,这可能是插件中的一个错误。以下是对您的表单的修改(请参阅fiddle)
<form action="email_submit.php" method="post" name="enterForm" id="enterForm">
<label for="email">Enter your email to play:</label>
<input type="text" name="email" id="email" value="" />
<input type="submit" value="Enter" name="submit" class="submit" />
<div id="error_container"></div>
</form>
$(function(){
$("#enterForm").validate({
rules: {
email: {
email: true,
required: true/*,
remote: {url:"email_valid.php", async:false}*/
}
},
messages:{
email:{
email: "Please enter a valid email address",
required: "Please enter an email address"/*,
remote: "That is not a valid domain"*/
}
},
submitHandler: function(form) {
var formData = $('form').serialize();
$.ajax({
type: 'POST',
url: "email_submit.php",
data: formData,
success: function(data){
if(data.subscriber && data.valid_email)
window.location = "calendar.html";
else if( !data.valid_email)
alert("Please enter a valid email");
else if( !data.subscriber)
alert("Open sign up form");
},
error: function(data){
alert("e:" + data);
console.log(data);
},
dataType: "JSON"
});
return false;
}, //uncomment this errorPlacement method
errorPlacement: function (error, element){
if( element.attr("name") == "email" ){
error.insertAfter("#error_container");
}
else
error.insertAfter(element);
}
});
});