jquery ajax form validation code example
Example 1: submit ajax form validation jquery
$('#form').validate({
... your validation rules come here,
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
$('#answers').html(response);
}
});
}
});
Example 2: How to call the ajax when form is valid
BY LOVE,
1- $("form").valid() is the main method which is checking the form is valid or not
2- 'btnsave' is the ID of the HTML BUTTON element.
3- Jquery pluggin should be added in this order
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
$('#btnSave').click(function () {
if ($("form").valid()) {
$.ajax({
url: 'http://localhost:3932/api/EmployeeService/Save',
type: 'POST',
dataType: 'json',
success: function () {
alert('Employee Save successfully');
},
error: function (xhr, textStatus, errorThrown) {
alert('Error occured');
}
});
}
});
Example 3: jquey validate and submit form using jquery ajax
$("#form_id").validate({
rules:{
name:"required",
email:{email: true,required: true},
mobile:{required : true,minlength:10},
},
messages: {
name:"Please fill name",
email:{email:"Enter Valid Email!",
required:"Enter Email!"
},
mobile:{minlength:"Please enter Valid Mobile No.",
required:"Please enter Mobile No."
},
},
submitHandler: function(form){
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
$('#answers').html(response);
}
});
}
});