Skip to content

Instantly share code, notes, and snippets.

@solancer
Created May 8, 2016 20:12
Show Gist options
  • Save solancer/3ff8524cb014b8c514ca4aa35d680d5f to your computer and use it in GitHub Desktop.
Save solancer/3ff8524cb014b8c514ca4aa35d680d5f to your computer and use it in GitHub Desktop.
My jquery.validate.boilerplate.js
// initialize validate plugin on the form
$('#contact-form').validate({
errorPlacement: function (error, element) {
var lastError = $(element).data('lastError'),
newError = $(error).text();
$(element).data('lastError', newError);
if(newError !== '' && newError !== lastError){
$(element).tooltipster('content', newError);
$(element).tooltipster('show');
}
},
success: function (label, element) {
$(element).tooltipster('hide');
},
rules: {
'con-name': {
required: true,
minlength: 2,
maxlength: 25
},
'con-mobile': {
required: true,
minlength: 8,
maxlength: 20
},
'con-email': {
required: true,
email: true,
},
'con-message': {
required: true,
maxlength: 500,
minlength: 10
}
},
messages: {
'con-name': "Please Specify Your Name",
'con-mobile': {
required: "Please Enter Your Mobile Number",
minlength: "Please enter a valid mobile number"
},
'con-email': {
required: "Please Enter Your Email Id",
email: "Please Enter a Valid Email Id"
},
'con-message': {
required: "Please Enter Your Message"
}
},
submitHandler: function (form) {
$('#divLoading').show();
var request;
// bind to the submit event of our form
// let's select and cache all the fields
var $inputs = $(form).find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $(form).serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request
request = $.ajax({
url: "/contact.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR) {
document.getElementById("contact-form").reset();
// $('#divLoading').hide();
// log a message to the console
alert("Form Submitted Sucessfully!");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown) {
// log the error to the console
console.error(
"The following error occured: " + textStatus, errorThrown);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment