
jQuery Form Validation + Bootstrap + Ajax
There are lots of ways to validate your forms but nothing is easier than using jQuery’s validation. So here is a small tutorial to help you implement this amazing plug-in altogether with Bootstrap + Ajax.
Let’s go into details of what is needed using a simple HTML form example.
1. Use Bootstrap Form + jQuery validation;
2. Use jQuery to define your own validation rules;
3. Create your own custom jQuery validation method
4. Submit your form using Ajax and display a Thank you message through Bootstrap Dialog;
First let’s start with a simple Bootstrap form
Notice we are loading the following assets in order to get the validation, bootstrap dialog to work.
CSS
//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css
//cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.9/css/bootstrap-dialog.min.css
JS
//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js
//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js
//cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.9/js/bootstrap-dialog.min.js
//cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js
Let’s start defining our validation rules in jQuery
Pay attention to the rules, messages and errorPlacement that will be used to write the error message inside <div class=”error”></div>
Let’s keep on building on this and add a few custom methods such as minimum age, zip code validation and such... Nothing changes with the HTML or libraries so here is the changes to the jQuery code:
You can see that I’ve added a few custom methods/criteria at the end of this file. Ex:
$.validator.addMethod("zipcodeUS", function(v, el) {
return this.optional(el) || /\d{5}-\d{4}$|^\d{5}$/.test(v);
}, "The specified US ZIP Code is invalid");and called them inside the validation plugin.
zip: {
required: true,
digits: true,
zipcodeUS: true, // there you go.
minlength: 5,
maxlength: 5
}You’ve also noticed the submitHandler: being used to make a Ajax call, pretty straight forward but the trick here is the code below that triggers the Thank You dialog DialogThanks()
success: function(html) {
setTimeout(function() {
DialogThanks();
}, 200);
}To see a working example of this tutorial check the JSFiddle below
That’s all folks.

If you enjoyed reading, please hit that little green heart!
Leo is a front-end and back-end web developer with 14+ years of experience working with clients ranging from small businesses to corporate companies. Writing about programming, sharing tricks and workflow best practices.