我正在尝试验证我的表单。例如,当用户没有输入任何值或空格时, jQuery验证插件将检测到错误并显示一条名为的错误消息,"请填写字段"或"没有空格"。如果验证正确,将在jQuery ajax的帮助下发出后HTTP请求,以将信息发送到服务器。目前,我能够验证但无法在用户单击提交时发出后HTTP请求。这是我的代码
<script>
function WebFormData(inLessonName) {
this.lessonName = inLessonName;
}
$('#dataForm').validate({
rules: {
lessonName: {
required: true,
nowhitespace: true
}
},
submitHandler: function (form) {
var collectedLessonName = $('#lessonName').val();
var webFormData = new WebFormData(collectedLessonName);
var webFormDataInString = JSON.stringify(webFormData);
$saveSessionSynopsisDataHandler = $.ajax({
method: 'POST',
url: '/API/Session',
dataType: 'json',
contentType: 'application/json;',
data: "'" + webFormDataInString + "'"
});
}
});
</script>
&#13;
<form id="dataForm" role="form" class="form-horizontal">
<label class="control-label col-md-4" for="lessonName">lesson name</label>
<input type="text" id="lessonName" name="lessonName" class="form-control font-bold"
maxlength="100" placeholder="lessonName" value="" />
<div class="col-md-10">
<div class="pull-right">
<input type="button" class="btn btn-primary" value="Save" id="saveButton" />
</div>
</div>
</form>
&#13;
答案 0 :(得分:1)
使用调用函数的onsubmit
form
方法。如果它返回false
,那么表单提交时,如果true
则不提交。只需用你的jquery添加我的例子
function validation(){
// check whatever you want to check here, return false if there is an error like white space
if (document.getElementById("name").value.length < 1) {
window.alert("fill the field");
return false; // form not submited
} else {
// if everything is fine then you can submit
return true;
}
}
<form onsubmit="return validation()">
Name: <input type="text" name="fname" id="name">
<input type="submit" value="Submit">
</form>