Reputation: 137
I am trying to validate my form. For example, when a user did not enter any value or white spaces, the jQuery validation plugin will detect the error and display an error message called, "please fill in the field" or "no white space". If the validation is correct, a post HTTP request will be issued with the help of jQuery ajax to send the information to the server. Currently, I am able to validate but unable to issue the post HTTP request when the user clicks submit. Here are my codes
<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>
<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>
Upvotes: 1
Views: 164
Reputation: 2729
Use the onsubmit
method for form
that calls a function. If it returns false
then it doesn't submit, if true
, the form submits. Just addapt my exemple with your 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>
Upvotes: 1