如果标准表单提交出现验证错误,如何防止表单提交?

时间:2013-11-27 17:17:14

标签: javascript jquery jquery-validate

我正在开发一个表单,其中包含一些文本字段和一些文件上传字段。一些javascript代码通过将其添加到div元素(id = wrapper)来动态地构建表单。对于我的knowlegde,无法通过ajax发送/上传文件,因此我选择“经典方式”发布表单,请参阅下面的代码。但是,我希望通过jquery验证验证文本字段;验证代码工作正常,但如果在验证错误的情况下如何防止表单提交?我假设我需要以某种方式覆盖标准表单提交处理程序,但不知道如何做到这一点...

//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>

2 个答案:

答案 0 :(得分:0)

引用OP:

  

“我想通过jquery验证文本字段验证”

由于您正在使用jQuery Validate插件,因此只需为submitHandler实施ajax回调即可。 As per documentation,这是“在经过验证后通过Ajax提交表单的正确位置”

尽管有其他人的回答,

  • 您不需要内联JavaScript。

  • 您不需要任何其他事件处理程序。


var completeform = $("#formNewAgreements");
completeform.validate({
    submitHandler: function(form) {
        // your ajax here
        return false;  // block default form action
    }
});

DEMO:http://jsfiddle.net/U4P3F/

答案 1 :(得分:-1)

试试这个

<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();'>