DotNetCurry Logo

Validate a Form using jQuery and Bootstrap Validator

Posted by: Irvin Dominin , on 8/22/2015, in Category jQuery and ASP.NET
Views: 142487
Abstract: HTML Form validation using jQuery and Bootstrap Validator with instant feedback

A typical task when developing a web site, is building a form to accept information, feedback or comments from visitors. But before submitting the form to the server, it becomes necessary for us to validate user input. You can validate phone numbers, emails, addresses, dates, credit cards etc. depending on your requirements.

 

In this article, I will show you a simple way to validate a form. For this purpose, we will use a plugin called Bootstrap Validator (project on http://bootstrapvalidator.com/ ).

This plugin is based on Twitter Bootstrap.js and offers some great and expanding list of features. Some of them are:

  • Bootstrap UI and web-fonts integration
  • Validator initialization based on plugin options or HTML data-attribute
  • Some built-in fields validators like: length of the content, date, credit card, IBAN, IMEI, phone, and some others
  • Custom fields validators
  • Possibility to add multiple validators to each field
  • Possibility to show a feedback icon on the field after its validation
  • Possibility to show the validation messages in a specific HTML element
  • Rich API’s to manipulate the plugin instance and behaviors
  • Some supported languages for localization

Bootstrap Validator Implementation

To use Bootstrap Validator, we first need to add the following dependencies in our project:

  • jQuery
  • Bootstrap (js and css)

To see it in action, we can build a form validation by checking that a typical contact form has a name, a valid e-mail address and a body text set.
Here are the dependencies included (from CDN):

<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Boostrap Validator</title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>  
  <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>  
  <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css"/>
  <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js"> </script>
</head>

Here is some simple HTML code representing the contact form:

<form id="contactForm" method="post" class="form-horizontal">
    <div class="form-group">
        <label class="col-md-3 control-label">Full name</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="fullName" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-3 control-label">Email</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="email" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-3 control-label">Title</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="title" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-3 control-label">Content</label>
        <div class="col-md-6">
            <textarea class="form-control" name="content" rows="5"></textarea>
        </div>
    </div>
    <!-- #messages is where the messages are placed inside -->
    <div class="form-group">
        <div class="col-md-9 col-md-offset-3">
            <div id="messages"></div>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-9 col-md-offset-3">
            <button type="submit" class="btn btn-default">Validate</button>
        </div>
    </div>
</form>

This is how the form will look like:

jquery-form-validate

 

Now enable form validation. The code is self-explanatory as we are defining certain fields with validators on them:

$(document).ready(function() {
    $('#contactForm').bootstrapValidator({
        container: '#messages',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            fullName: {
                validators: {
                    notEmpty: {
                        message: 'The full name is required and cannot be empty'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: 'The email address is required and cannot be empty'
                    },
                    emailAddress: {
                        message: 'The email address is not valid'
                    }
                }
            },
            title: {
                validators: {
                    notEmpty: {
                        message: 'The title is required and cannot be empty'
                    },
                    stringLength: {
                        max: 100,
                        message: 'The title must be less than 100 characters long'
                    }
                }
            },
            content: {
                validators: {
                    notEmpty: {
                        message: 'The content is required and cannot be empty'
                    },
                    stringLength: {
                        max: 500,
                        message: 'The content must be less than 500 characters long'
                    }
                }
            }
        }
    });
});

Now submit the form without filling any details and you will see the following validations appear.

jquery-form-errors

You will also observe that as we fill in the details, the valid fields turn green (with a tickmark), thereby giving immediate feedback to users.

jquery-live-validate

And that’s it. This way, the form will not be submitted until the required/validated fields are correctly filled.

Never forget to validate the submitted data to server. Also remember to perform server-side validation in addition to client side validation as JavaScript can be turned off by the user, there by bypassing the validation on client-side!

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Irvin Dominin is currently working as lead of a technical team in SISTEMI S.p.A. (Turin, Italy) on .NET, jQuery and windows Projects. He is an active member on StackOverflow. You can reach him at: irvin[dot]dominin[attherate]gmail[dot]com or on LinkedIn


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!