when the jquery validation plugin is used for validating the form data, such as below:
html code:
<form method="post" action="" id="buy-form" novalidate="novalidate"> <table style="margin:35px 150px 0 150px;"> <tr> <td class="info-title">预定版本<input type="hidden" name="versionName" id="versionName" value="" /></td> <td class="info-content-version">免费版本</td> </tr> <tr> <td class="info-title">联系人</td> <td class="info-content"><p><input class="required" type="text" placeholder="请输入联系人姓名(必填)" style="width:330px;" name="name" id="applicants-name" /></p></td> </tr> <tr> <td class="info-title">电话</td> <td class="info-content"><input type="text" placeholder="座机区号" style="width:100px;" name="locationNo" id="locationNo" /> - <input type="text" placeholder="座机号码/手机号码(必填)" style="width:209px;" name="phone" id="phone" /></td> </tr> <tr> <td class="info-title">邮箱</td> <td class="info-content"><input type="text" placeholder="请输入联系人邮箱地址(必填)" style="width:330px;" name="email" id="email" /></td> </tr> <tr> <td class="info-title">公司名称</td> <td class="info-content"><input type="text" placeholder="请输入联系人公司名称(必填)" style="width:330px;" name="companyName" id="companyName" /></td> </tr> </table> </form>
js code:
var form = $("#buy-form"); form.validate({ errorElement: "span", rules: { "name": { required: true }, "phone": { required: true }, "email": { required: true }, "companyName": { required: true } }, messages: { "name": { required: "请输入联系人姓名", }, "phone": { required: "请输入号码", }, "email": { required: "请输入邮箱地址", }, "companyName": { required: "请输入公司名称", } } });
ajax submit code:
$(".submit").click(function(){ var form = $("#buy-form"); var $alertDialog = $("#alert-dialog"); form.submit(function (event) { event.preventDefault();});//阻止在数据校验失败的情况下提交表单;绑定事件,但不触发; form.submit();//触发绑定事件; var validator = form.validate(); if (validator.numberOfInvalids() <= 0) {//判断加入所有校验都通过后再做ajax提交; $.ajax({ url: "Home/SubmitPurchaseApplication", data: $("#buy-form").serialize(), type: "post", async: false, success: function (data) { freeDialog.dialog("close"); $("#alert-title h3").text("购买成功!"); $("#alert-message p").text("您的购买申请已经提交,我们会尽快联系您"); ShowAlertDialog(); //异步提交后弹框提示; }, error: function () { freeDialog.dialog("close"); $("#alert-title h3").text("购买失败!"); $("#alert-message p").text("您的购买申请出现异常,请重新申请"); ShowAlertDialog(); } }); } });