[英]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.