我在这里撕扯我的头发试图获得一个jquery验证,以便与我的表格很好地搭配。
验证似乎不起作用。表单只是提交给页面。我可以简要地看一下页面提交之前出现的验证错误消息......
我的代码:
//HTML form
<form id="form_scheduleEvent" name="form_scheduleEvent">
<label for="name">Name:</label><input class="short" type="text" name="name" id="name" />
<label for="address">Address:</label><input type="text" name="address" id="address" />
<label for="phone">Phone:</label><input type="text" name="phone" id="phone" />
<label for="comments">Comments:</label><textarea name="comments" id="comments" /></textarea>
<input type="submit" id="submitRequest" value="Add"/>
</form>
//jquery
//Validation rules
$('#form_scheduleEvent').validate({
rules: {
name : {required: true, maxlength: 45},
address : {required: true, maxlength: 45},
phone : "required"
}
});
$('#submitRequest').click(function(){
$.ajax({
type: "POST",
url: "common/ajax_event.php",
data: formSerialized,
timeout:3000,
error:function(){alert('Error');},
success: function() {alert('It worked!');}
});
return false;
});
我尝试更新到jquery和jquery.validation的最新版本....
任何帮助将不胜感激!感谢。
更新
//The validation is working, but I can't even get the alert to show....
$('#form_scheduleEvent').validate({
rules: {
name : {required: true, maxlength: 45},
address : {required: true, maxlength: 45},
phone : "required",
submitHandler: function(){
alert('test');
}
}
});
答案 0 :(得分:5)
您应该将您的AJAX提交调用移动到由validate插件中的提交回调触发:
$('#form_scheduleEvent').validate({
rules: {
name : {required: true, maxlength: 45},
address : {required: true, maxlength: 45},
phone : "required",
submitHandler: function(form) { DoSubmit(); }
}
});
function DoSubmit(){
$.ajax({
type: "POST",
url: "common/ajax_event.php",
data: formSerialized,
timeout:3000,
error:function(){alert('Error');},
success: function() {alert('It worked!');}
}
答案 1 :(得分:4)
感谢大家的回复。
我最终在以下代码中包装了原始代码的ajax调用部分:
if($('#form_scheduleEvent').valid() == true){
//Process ajax request...
}
return false;
答案 2 :(得分:4)
如果你提出一个没有匹配方法的规则,可能会发生这种情况,请参见&amp;投票给我的错误报告。 https://github.com/jzaefferer/jquery-validation/issues/1212
答案 3 :(得分:2)
您在验证检查之外调用表单提交。你可能想要这样的东西:
$('#form_scheduleEvent').validate({
rules: {
name : {required: true, maxlength: 45},
address : {required: true, maxlength: 45},
phone : "required",
success: function() {
$.ajax({
type: "POST",
url: "common/ajax_event.php",
data: formSerialized,
timeout:3000
}
}
});
答案 4 :(得分:1)
正如Grillz所说,您要单独提交和验证,您应该在点击事件中明确地调用验证来执行它。
反之亦然,Paddy表示! ;)
答案 5 :(得分:1)
我同意Josh Ribakoff的观点 请参阅:https://github.com/jzaefferer/jquery-validation/issues/1212
中的错误答案 6 :(得分:0)
$('#form_scheduleEvent').validate({
rules: {
name : {required: true, maxlength: 45},
address : {required: true, maxlength: 45},
phone : "required"
},
submitHandler: function(){
alert('test');
}
});
提交处理程序应该是外部规则。 : - )