Powerful Form Field Validator For Jquery And Bootstrap Using Bootstrap Validator

Introduction

 
Client-side validation has been growing very fast due to its smaller impact on the server and you can reduce the round trips also by just filtering the required information in the form of form field validations.
 
There are many types of form fields which need a strict validation, not a single one, like field may allow you to only enter only the numbers, characters or both, but also it should require you to check that the field should not be empty having a specific format, either for example with password field it should have a check to contain special characters in field followed by single capital case and a more interesting password strength and length of password should be between 8 to 15 or like this. Would you guess you can do it in fewer lines of code? The answer to this question is NO.
 
Why because you cannot handle it;  you require more time to code and use a lot of things to do the one kind of task to validate proper password standards. So here I want to introduce you to the best validation library which has a lot of more support for not only bootstrap but for Foundation, Pure, Semantic UI, UI Kit and lots more.
 
You can read more about the library and its documentation from here.
 
Before starting to implement read the getting started guide from here.
 
There are many forms of field validators in the market but what makes it best? Check out the features list.
 
Features of Form Validator
  • Language packs included supporting multiple language packs.
  • Glyph icons to validate input by using icons.
  • Support for multiple frameworks bootstrap, Foundation, Semantic UI and lot of others more.
  • Compatible with HTML5 Input types
  • Compatible with Modern Browsers.
  • Supports error message of type tooltip, message and lot of other ways to check validity.
  • Over 51 built-in validators for different form fields.
  • having add-ons like multiple languages and re-captcha support
This is all the features it supports, now let's move on to use it in web application.
 
Step 1:
For every JQuery Library, it is necessary to first include scripts file into the application and reference it on the page. First, make a choice from the supported frameworks and select the one you are working with and include it. For tutorial purposes, I am using bootstrap here. Firstly, add the following basic required jquery and Twitter bootstrap script to the head section of the page.
 
Note: Form validation requires jquery version => 1.9.1
  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>    
  2. <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" />    
  3. <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>  
Step 2: 
Add bootstrap validator scripts to the head section just below to the firstly added scripts. 
  1. <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.5.3/css/bootstrapValidator.css"></script>    
  2. <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.5.3/js/bootstrapValidator.min.js"></script>  
I am using the CDN files here you may download scripts and follow the instructions in getting started panel to integrate with the best of your criteria.
 
Step 3:
Let’s build the form which can be validated through the bootstrap validator. I am using a signup form for this demo as it contains lots of things to cover.
  1. <form id="SignupForm" method="post" class="form-horizontal">    
  2.     <div class="form-group"> <label class="col-lg-3 control-label">Username</label>    
  3.         <div class="col-lg-5"> <input type="text" class="form-control" name="username" /> </div>    
  4.     </div>    
  5.     <div class="form-group"> <label class="col-lg-3 control-label">Email address</label>    
  6.         <div class="col-lg-5"> <input type="text" class="form-control" name="email" /> </div>    
  7.     </div>    
  8.     <div class="form-group"> <label class="col-lg-3 control-label">Password</label>    
  9.         <div class="col-lg-5"> <input type="password" class="form-control" name="password" /> </div>    
  10.     </div>    
  11.     <div class="form-group"> <label class="col-lg-3 control-label">Retype password</label>    
  12.         <div class="col-lg-5"> <input type="password" class="form-control" name="confirmPassword" /> </div>    
  13.     </div>    
  14.     <div class="form-group"> <label class="col-lg-3 control-label" id="captchasignup"></label>    
  15.         <div class="col-lg-2"> <input type="text" class="form-control" name="captcha" /> </div>    
  16.     </div>    
  17.     <div class="form-group">    
  18.         <div class="col-lg-9 col-lg-offset-3"> <button type="submit" class="btn btn-primary">Sign up</button> </div>    
  19.     </div>    
  20. </form>   
    UI View looks like this after adding form and applying bootstrap. 
     
     
    I am using Html elements for validating form fields in asp.net, if you are using server-side controls then find this Tutorial.
     
    You can see the classes used in the form fields are all bootstrap, for example, the class ="form-horizontal" used in the form tag is specifically used in bootstrap to horizontally align the form fields like label and input control.
     
    Step 4:
    Now we come to our important work which is validating the form fields section via bootstrap validator script. Before discussing deep the script section let’s have a look at the syntax of writing script which is given below:
    1. $(formSelector).formValidation    
    2. ({    
    3.     // Indicate the framework      
    4.     // It can be: bootstrap, foundation, pure, semantic, uikit      
    5.     framework: 'bootstrap',    
    6.     // ... Form settings go here ...      
    7.     fields:    
    8.     {    
    9.         fieldName:    
    10.         {    
    11.             // ... Field settings go here ...      
    12.             validators: {    
    13.                 specificValidatorName: {    
    14.                     // ... common validator settings go here ...      
    15.                     // ... specific validator settings ...      
    16.                 }    
    17.             }    
    18.         }    
    19.     }    
    20. });   
      Syntax contains comments for better understanding. 
       
      We have initialized our script in the document. The ready function of jQuery,
      1. <script type="text/javascript">    
      2.     $(document).ready(function()    
      3.     {    
      4.         // Generate a simple captcha      
      5.         function randomNumber(min, max)    
      6.         {    
      7.             return Math.floor(Math.random() * (max - min + 1) + min);    
      8.         };    
      9.         $('#captchasignup').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' '));    
      10.         $('#SignupForm).bootstrapValidator    
      11.           ({      
      12.             message: 'This value is not valid', fields:    
      13.             {    
      14.                 username: {    
      15.                     message: 'The username is not valid',    
      16.                     validators: {    
      17.                         notEmpty: {    
      18.                             message: 'The username is required and can\'t be empty'    
      19.                         },    
      20.                         stringLength: {    
      21.                             min: 6,    
      22.                             max: 30,    
      23.                             message: 'The username must be more than 6 and less than 30 characters long'    
      24.                         },    
      25.                         regexp: {    
      26.                             regexp: /^[a-zA-Z0-9_\.]+$/,    
      27.                             message: 'The username can only consist of alphabetical, number, dot and underscore'    
      28.                         },    
      29.                         different: {    
      30.                             field: 'password',    
      31.                             message: 'The username and password can\'t be the same as each other'    
      32.                         }    
      33.                     }    
      34.                 },    
      35.                 email: {    
      36.                     validators: {    
      37.                         notEmpty: {    
      38.                             message: 'The email address is required and can\'t be empty'    
      39.                         },    
      40.                         emailAddress: {    
      41.                             message: 'The input is not a valid email address'    
      42.                         }    
      43.                     }    
      44.                 },    
      45.                 password: {    
      46.                     validators: {    
      47.                         notEmpty: {    
      48.                             message: 'The password is required and can\'t be empty'    
      49.                         },    
      50.                         identical: {    
      51.                             field: 'confirmPassword',    
      52.                             message: 'The password and its confirm are not the same'    
      53.                         },    
      54.                         different: {    
      55.                             field: 'username',    
      56.                             message: 'The password can\'t be the same as username'    
      57.                         }    
      58.                     }    
      59.                 },    
      60.                 confirmPassword: {    
      61.                     validators: {    
      62.                         notEmpty: {    
      63.                             message: 'The confirm password is required and can\'t be empty'    
      64.                         },    
      65.                         identical: {    
      66.                             field: 'password',    
      67.                             message: 'The password and its confirm are not the same'    
      68.                         },    
      69.                         different: {    
      70.                             field: 'username',    
      71.                             message: 'The password can\'t be the same as username'    
      72.                         }    
      73.                     }    
      74.                 },    
      75.                 captcha: {    
      76.                     validators: {    
      77.                         callback: {    
      78.                             message: 'Wrong answer',    
      79.                             callback: function(value, validator) {    
      80.                                 var items = $('#captchaOperation').html().split(' '),    
      81.                                     sum = parseInt(items[0]) + parseInt(items[2]);    
      82.                                 return value == sum;    
      83.                             }    
      84.                         }    
      85.                     }    
      86.                 }    
      87.             }    
      88.         });    
      89.     });    
      90. </script>   
        The username has been checked across three ways firstly your username should be between 6 and 30 characters. Secondly, it should contain only alphabet letters no other characters allowed like numbers. And thirdly, it should not be empty. For email, it is necessary that it should not be empty as well as a valid email. The password is a bit complex and tricky to check as it has many cases but the validator handles it beautifully. Have a look at the password section, the password should not be empty, and it does not contain your username and it also checks the confirm password. 
         
        This is all about the demo but this is the start there are many complex things that are handled through the use of this validator script.
         
        Final Output after implementing bootstrap validator.
         
         


        Similar Articles