[英]how to prevent form submission in case of valiadtion error with standard form submission?
我正在开发一种表单,其中包含一些文本字段和一些用于文件上传的字段。 一些JavaScript代码通过将表单添加到div元素(id = wrapper)中来动态构建表单。 据我所知,无法通过ajax发送/上传文件,因此我选择了“经典方式”来发布表单,请参见下面的代码。 但是,我想通过jquery validate来验证文本字段。 验证代码可以正常工作,但是如果发生验证错误,如何防止表单提交? 我认为我需要某种方式来覆盖标准表单提交处理程序,但是不知道该怎么做...
//original form submit code
$("#formNewAgreements").submit(function(){
var form = $("#formNewAgreements");
form.validate();
if(form.valid()){ //only submit via ajax if javascript validation has been performed successfully
$.ajax({
type: "POST",
url: "suppladmin_agreementsetup_submit_x1.php",
data: $("#formNewAgreements").serialize(),
dataType: "json",
success: function(msg){
if(msg.statusgeneral == 'success'){
$("#wrapper").children().remove(); //remove current New Agreements form
SetupAgreements();
}
else
{
$("#errorbox").html(msg.statusgeneral);
}//else
}, //succes: function
error: function(){
$("#errorbox").html("There was an error submitting the form. Please try again.");
}
});//.ajax
//make sure the form doesn't post
return false;
} //if(form.valid()
});//$("#myForm").submit()
//validation code for validing the textfields
var completeform = $("#formNewAgreements");
completeform.validate();
//html code form
<form id="formNewAgreements" name="formNewAgreements" action="submit_x1.php" method="post" enctype="multipart/form-data" target="hidden-form" >
<!--<form id="formNewAgreements" name="formNewAgreements" action="" method="post" autocomplete="on">-->
<a href="#" id="add-form">Add agreement</a>
<div id="wrapper"></div> <!--anchor point for adding set of form fields -->
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
<input type="submit" name="submitForm" value="Confirm">
</form>
<iframe style="display:inline" name="hidden-form" width="200" height="20"></iframe>
报价OP:
“我想通过jquery validate验证文本字段”
由于您使用的是jQuery Validate插件,因此只需为ajax
实现submitHandler
回调即可。 根据文档 ,这是“在验证后通过Ajax提交表单的正确位置” 。
尽管有其他人的回答,
您不需要内联JavaScript。
您不需要任何其他事件处理程序。
var completeform = $("#formNewAgreements");
completeform.validate({
submitHandler: function(form) {
// your ajax here
return false; // block default form action
}
});
演示: http : //jsfiddle.net/U4P3F/
尝试这个
<input type="submit" name="submitForm" value="Confirm" onclick='completeform.validate();' />
在这种情况下,您的validate方法应返回true或false,具体取决于表单是否有效。
编辑:正如@ lex82提到的做到这一点的正确方法是将处理程序添加到表单提交。 将表单标签更改为:
<form id="formNewAgreements" name="formNewAgreements" action="submit_x1.php" method="post" enctype="multipart/form-data" target="hidden-form" onsubmit='completeform.validate();'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.