Add Validation To A Web Form Using IGValidator

Introduction

 
Data validation is one of the most common but required functionalities in a modern Web page. Implementing data validation can be time-consuming for web developers. Infragistics provides a JavaScript validator control, IGValidator that can be used to validate a form’s input controls without writing too much code.
 
It can be used with most of the common form input elements such as Input, Radio button, and Checkbox. This control provides a very high interactive design for success and failure of data validation and because it’s written in JavaScript, which makes it very efficient and easy to code. IGValidator provides various validation rules such as required field and data types such as number, date, card, email, and also custom type. IGValidator is a part of IgniteUI for JavaScript provided by Infragistics.
 
What we will cover in this article?
 
In this article, we’ll cover some of the common rules of input validation and how to apply them to various controls.
  • Required Validation
  • Compare Validation
  • Masking
  • Multi Selection in Dropdown
  • Ignite Date Picker with validation
  • Validate Common Controls (i.e textbox, dropdown, checkbox, datepicker, etc. )
Let's get started
 
Before anything else, make sure you install Ignite UI for JavaScript and HTML 5.
 
Let’s start by creating a simple HTML page. You can use any tool of your choice. We’ll use an HTML page to implement validations so that you can implement in any project.
 
First, we need to add the CSS and CDN scripts provided by Infragistics as shown in Listing 1.
  1. <!--  CSS files -->    
  2. <link href="http://cdn-na.infragistics.com/igniteui/2018.1/latest/css/themes/infragistics/ infragistics.theme.css" rel="stylesheet" />    
  3. <link href="http://cdn-na.infragistics.com/igniteui/2018.1/latest/css/structure/infragistics.css" rel="stylesheet" />    
  4. <link href="https://www.igniteui.com/igniteui/css/themes/infragistics/infragistics.theme.css" rel="stylesheet"/>    
  5. <!--  Script files -->    
  6. <script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js"></script>    
  7. <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>    
  8. <script src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>    
  9.     
  10. <!--Ignite UI Required Combined JavaScript Files-->    
  11. <script src="http://cdn-na.infragistics.com/igniteui/2018.1/latest/js/infragistics.core.js"> </script>    
  12. <script src="http://cdn-na.infragistics.com/igniteui/2018.1/latest/js/infragistics.lob.js"></script>   
Listing 1- Required Validation
 
Now, let’s add two simple HTML input controls for First Name and Last Name to validate as shown in Listing 2.
  1. <form id="validationForm" action="" method="post">    
  2.         <div class="group-fields clearfix">    
  3.             <div class="odd">    
  4.                 <label>First name*</label>    
  5.                 <input class="group" type="text" id="firstName" />    
  6.             </div>    
  7.             <div class="even">    
  8.                 <label>Last name*</label>    
  9.                 <input class="group" type="text" id="lastName" />    
  10.             </div>    
  11.         </div>    
  12. </form> 
Listing 2
 
To validate controls in the page, first, we need to mark the form tag as igValidator then in fields option add those fields and their validation options. We also use a custom regex function which returns true if the field has only uppercase or lowercase text. Refer to listing 3.
  1. $('#validationForm').igValidator({    
  2.         onsubmit: true,    
  3.         successMessage: "Valid",    
  4.         fields: [{    
  5.             required: true,    
  6.             selector: "#firstName",    
  7.             valueRange: [2],    
  8.             onblur: true,    
  9.             custom: function (value, fieldOptions) {    
  10.                 var myRegEx = /^[a-zA-Z]+$/;    
  11.                 var isValid = myRegEx.test(value);    
  12.                 return isValid;    
  13.             }    
  14.         },    
  15.         {    
  16.             required: true,    
  17.             selector: "#lastName",    
  18.             valueRange: [2],    
  19.             onblur: true,    
  20.             custom: function (value, fieldOptions) {    
  21.                      var myRegEx = /^[a-zA-Z]+$/;    
  22.                  var isValid = myRegEx.test(value);    
  23.                 return isValid;    
  24.                    }    
  25.                }]    
  26. );   
Listing 3
 
Hit save and open the HTML page in the Web browser. Refer to Figure 1.
 
JavaScript
 Figure 1 
 

Compare Validation

 
To check if two input fields have the same values or not, we use compare validation.
 
Let’s add two common fields which mostly use comparison validation like password as shown in Listing 4
  1. <div class="group-fields clearfix">    
  2.           <div class="odd">    
  3.                <label>Create password*</label>    
  4.                <input class="group" type="password" id="createPassword" />    
  5.           </div>    
  6.           <div class="even">    
  7.                <label>Confirm password*</label>    
  8.                <input class="group" type="password" id="confirmPassword" />    
  9.           </div>    
  10.  </div>  
Listing 4
 
Let's add javascript to make the password and the confirm password work and also add the regex for password strength as shown in Listing 5.
  1. $('#validationForm').igValidator({    
  2.          onsubmit: true,    
  3.          successMessage: "Valid",    
  4.          fields: [    
  5.  {    
  6.                     required: true,    
  7.                     selector: "#createPassword",    
  8.                     onblur: true,    
  9.                     errorMessage: "Should contain at least 8 characters, 1 number, 1 lowercase     
  10. character (a-z), 1 uppercase character",    
  11.                     custom: function(value, fieldOptions){    
  12.                         var myRegEx  = /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/;    
  13.                         var isValid = myRegEx.test(value);    
  14.                         return isValid;    
  15.                     }    
  16.                 },    
  17.                 {    
  18.                     required: true,    
  19.                     selector: "#confirmPassword",    
  20.                     equalTo: "#createPassword",    
  21.                     onblur: true,    
  22.                 }]    
  23. });   
Listing 5
 
JavaScript 
Figure 2
 

Masking

 
We can mask any input field using IgMasking.
 
Let’s say we have to mask a phone number, add another input field as shown in Listing 6.
  1. <div class="even">    
  2.    <label>Mobile phone</label>    
  3.    <input class="group" type="text" id="phone" />    
  4. </div>   
Listing 6
 
After adding Html, we can write 3 lines of code to implement masking as shown in Listing 7. This code is simply placed in the load function of the page.
  1. $("#phone").igMaskEditor({    
  2. inputMask: "(\+\\91) 0000-000000" });   
Listing 7
 
The output is like Figure 3.
 
JavaScript
 Figure 3 
 

Multi Selection in Dropdown

 
First, let's add simple div in html with id as shown in Listing 7.
  1. <div class="odd">    
  2.             <label>Your interests (Select at least 2)*</label>    
  3.             <div id='igComboInterests'></div>    
  4.         </div>   
Listing 7
 
Now let’s create some data and then bind that data to a div and then enable multi selection feature as shown in Listing 8.
  1. var data = [    
  2.               { ID: "ID101", Name: "Business", Code: 101 },    
  3.               { ID: "ID102", Name: "Cooking", Code: 102 },    
  4.               { ID: "ID103", Name: "Fashion", Code: 103 },    
  5.               { ID: "ID104", Name: "Lifestyle", Code: 104 },    
  6.               { ID: "ID105", Name: "Photography", Code: 105 },    
  7.               { ID: "ID106", Name: "Sports", Code: 106 }];    
  8.     
  9.             $('#igComboInterests').igCombo({    
  10.               inputName: "products",    
  11.               dataSource: data,    
  12.               allowCustomValue: true,    
  13.               textKey: 'Name',    
  14.               valueKey: "ID",    
  15.               multiSelection: {    
  16.                   enabled: true    
  17.               }    
  18.           });    
  19.     
  20. ('#validationForm').igValidator({    
  21.        onsubmit: true,    
  22.        successMessage: "Valid",    
  23.        fields: [    
  24. required: true,    
  25.     selector: "#igComboInterests",    
  26.     onchange: true,    
  27.     lengthRange: [2]]    
  28. ;   
Listing 8
 
The output will be as in Figure 4.
 
JavaScript
 Figure 4 
 

Ignite Date Picker with validation

 
Let’s add input tag inside div as shown in Listing 9.
  1. <div class="odd">    
  2.      <label>Date of birth*</label>    
  3.      <input class="group" id="dateOfBirth" />    
  4. </div>   
Listing 9
 
Now add javascript for Ignite DatePicker and validation as in Listing 10. When we mark an input as igDatePicker, it restricts the user to enter text in a field by default. We can also set the minimum and maximum dates for DatePicker.
  1. $("#dateOfBirth").igDatePicker({    
  2.                datepickerOptions: { minDate: new Date(1920, 0, 1), maxDate: new Date() }    
  3.            });    
  4.     
  5. $('#validationForm').igValidator({    
  6.         onsubmit: true,    
  7.         successMessage: "Valid",    
  8.         fields: [    
  9.     
  10.                 required: true,    
  11.                 selector: "#dateOfBirth",    
  12.                 date: true,    
  13.                 onblur: true    
  14.             }]    
  15. );   
Listing 10
 
When you click on the datepicker default Infragistics Date will pop up. Refer to Figure 5.
 
JavaScript
Figure 5 
 
To make the form look better I’ve also added some CSS to the form which is as shown in Listing 11.
  1. <style>    
  2.        .group-fields {    
  3.            margin-bottom:20px;    
  4.        }    
  5.        .group-fields .odd {    
  6.            float:left;    
  7.            width:262px;    
  8.        }    
  9.        .group-fields .even{    
  10.            float:left;    
  11.            margin-left:20px;    
  12.        }    
  13.        .group-fields label {    
  14.            display: block;    
  15.            line-height: 20px;    
  16.            font-family: 'Open Sans',Arial,sans-serif;    
  17.            font-size: 13px;    
  18.        }    
  19.        .group-fields .ui-igedit-container {    
  20.            box-sizing: content-box;    
  21.        }    
  22.        .group-fields input.group {    
  23.            width:258px;    
  24.            height:32px;    
  25.        }    
  26.        .group-fields .ui-igedit-container,.group-fields .ui-igcombo-wrapper {    
  27.            width:260px;    
  28.            height:34px;    
  29.        }    
  30.        .group-fields .ui-igpopover {    
  31.            width:260px;    
  32.        }    
  33.        .group-fields input.group {    
  34.            border-style: solid;    
  35.            border-width: 1px;    
  36.            border-color:#bcbcbc;    
  37.        }    
  38.        .group-fields input.group:hover {    
  39.            border-color:#444;    
  40.        }    
  41.        .group-fields .ui-widget.ui-ignotify.ui-ignotify-inline {    
  42.            margin-bottom:0;    
  43.        }    
  44.        .group-fields input.group.ui-ignotify-error {    
  45.            border-color:#f33;    
  46.        }    
  47.        #igCheckboxAccept, #igCheckboxSubscribe {    
  48.            float:left;    
  49.            margin-right: 5px;    
  50.        }    
  51.        .group-fields .inline {    
  52.            display:inline;    
  53.        }    
  54.        .clearfix:after {    
  55.            content: "";    
  56.            display: table;    
  57.            clear: both;    
  58.        }    
  59.        @media screen and (max-width:610px) {    
  60.            .group-fields .odd {    
  61.                float:left;    
  62.                width:202px;    
  63.            }    
  64.            .group-fields input.group {    
  65.                width:200px;    
  66.            }    
  67.            .group-fields .ui-igedit-container,.group-fields .ui-igcombo-wrapper {    
  68.                width:202px;    
  69.            }    
  70.            .group-fields .ui-igpopover {    
  71.                width:202px;    
  72.            }    
  73.        }    
  74.        @media screen and (max-width:478px) {    
  75.            .group-fields {    
  76.                margin-bottom:0;    
  77.            }    
  78.            .group-fields .odd, .group-fields .even {    
  79.                margin-bottom: 5px;    
  80.            }    
  81.            .group-fields .odd {    
  82.                float:none;    
  83.                width:262px;    
  84.            }    
  85.            .group-fields .even {    
  86.                margin-left:0;    
  87.            }    
  88.            .group-fields input.group {    
  89.                width:258px;    
  90.                height:32px;    
  91.            }    
  92.            .group-fields .ui-igedit-container,.group-fields .ui-igcombo-wrapper {    
  93.                width:260px;    
  94.                height:34px;    
  95.            }    
  96.            .group-fields .ui-igpopover {    
  97.             width:260px;    
  98.             }    
  99.        }    
  100.    </style>   
Listing 11
 

Validate Common Controls

 
To merge all controls of Html and Javascript refer to Listing 12 & Listing 13.
  1. <form id="validationForm" action="" method="post">    
  2.         <div class="group-fields clearfix">    
  3.             <div class="odd">    
  4.                 <label>First name*</label>    
  5.                 <input class="group" type="text" id="firstName" />    
  6.             </div>    
  7.             <div class="even">    
  8.                 <label>Last name*</label>    
  9.                 <input class="group" type="text" id="lastName" />    
  10.             </div>    
  11.         </div>    
  12.         <div class="group-fields clearfix">    
  13.             <div class="odd">    
  14.                 <label>Email*</label>    
  15.                 <input class="group" type="text" id="email" />    
  16.             </div>    
  17.             <div class="even">    
  18.                 <label>Mobile phone</label>    
  19.                 <input class="group" type="text" id="phone" />    
  20.             </div>    
  21.         </div>    
  22.         <div class="group-fields clearfix">    
  23.             <div class="odd">    
  24.                 <label>Create password*</label>    
  25.                 <input class="group" type="password" id="createPassword" />    
  26.             </div>    
  27.             <div class="even">    
  28.                 <label>Confirm password*</label>    
  29.                 <input class="group" type="password" id="confirmPassword" />    
  30.             </div>    
  31.         </div>    
  32.         <div class="group-fields clearfix">    
  33.             <div class="odd">    
  34.                 <label>Date of birth*</label>    
  35.                 <input class="group" id="dateOfBirth" />    
  36.             </div>    
  37.             <div class="even">    
  38.                 <label>Gender*</label>    
  39.                 <input id='gender' />    
  40.             </div>    
  41.         </div>    
  42.         <div class="group-fields clearfix">    
  43.             <div class="odd">    
  44.                 <label>Your interests (Select at least 2)*</label>    
  45.                 <div id='igComboInterests'></div>    
  46.             </div>               
  47.         </div>    
  48.         <div class="group-fields clearfix">    
  49.             <div class="odd">    
  50.                 <label class="inline">I accept the Terms and Conditions *</label>    
  51.                 <div id="igCheckboxAccept"></div>    
  52.             </div>    
  53.             <div class="even">    
  54.                 <label class="inline">Subscribe for our daily mail digest</label>    
  55.                 <div id="igCheckboxSubscribe"></div>    
  56.             </div>    
  57.         </div>    
  58.         <input type="submit" value="Sign Up" />    
  59.     </form>   
Listing 12
 
  1. <script>    
  2.         $(function () {    
  3.             var data = [    
  4.                 { ID: "ID101", Name: "Business", Code: 101 },    
  5.                 { ID: "ID102", Name: "Cooking", Code: 102 },    
  6.                 { ID: "ID103", Name: "Fashion", Code: 103 },    
  7.                 { ID: "ID104", Name: "Lifestyle", Code: 104 },    
  8.                 { ID: "ID105", Name: "Photography", Code: 105 },    
  9.                 { ID: "ID106", Name: "Sports", Code: 106 }];    
  10.     
  11.             $('#gender').igTextEditor({    
  12.                 inputName: "gender",    
  13.                 listItems: ["Male""Female"]    
  14.             });    
  15.     
  16.             $("#phone").igMaskEditor({    
  17.                 inputMask: "(\\0\\01) 000-0000"    
  18.             });    
  19.     
  20.             $('#igComboInterests').igCombo({    
  21.                 inputName: "products",    
  22.                 dataSource: data,    
  23.                 allowCustomValue: true,    
  24.                 textKey: 'Name',    
  25.                 valueKey: "ID",    
  26.                 multiSelection: {    
  27.                     enabled: true    
  28.                 }    
  29.             });    
  30. ….              
  31.     
  32.             $("#dateOfBirth").igDatePicker({    
  33.                 datepickerOptions: { minDate: new Date(1920, 0, 1), maxDate: new Date(2015, 0, 1) }    
  34.             });    
  35.     
  36.            $("#igCheckboxAccept").igCheckboxEditor();    
  37.            $("#igCheckboxSubscribe").igCheckboxEditor();    
  38.            $('#validationForm').igValidator({    
  39.                 onsubmit: true,    
  40.                 successMessage: "Valid",    
  41.                 fields: [{    
  42.                     required: true,    
  43.                     selector: "#firstName",    
  44.                     valueRange: [2],    
  45.                     onblur: true,    
  46.                     custom: function (value, fieldOptions) {    
  47.                         var myRegEx = /^[a-zA-Z]+$/;    
  48.                         var isValid = myRegEx.test(value);    
  49.                         return isValid;    
  50.                     }    
  51.                 },    
  52.                 {    
  53.                     required: true,    
  54.                     selector: "#lastName",    
  55.                     valueRange: [2],    
  56.                     onblur: true,    
  57.                     custom: function (value, fieldOptions) {    
  58.                         var myRegEx = /^[a-zA-Z]+$/;    
  59.                         var isValid = myRegEx.test(value);    
  60.                         return isValid;    
  61.                     }    
  62.                 },    
  63.                 {    
  64.                     required: true,    
  65.                     selector: "#dateOfBirth",    
  66.                     date: true,    
  67.                     onblur: true    
  68.                 },    
  69.                 {    
  70.                     required: true,    
  71.                     selector: "#gender",    
  72.                     gender: true,    
  73.                     onblur: true    
  74.                 },    
  75.                 {    
  76.                     required: true,    
  77.                     selector: "#email",    
  78.                     email: true,    
  79.                     onblur: true    
  80.                 },    
  81.                 {    
  82.                     required: true,    
  83.                     selector: "#createPassword",    
  84.                     onblur: true,    
  85.                     errorMessage: "Should contain at least 8 characters, 1 number, 1 lowercase     
  86. character (a-z), 1 uppercase character",    
  87.                     custom: function(value, fieldOptions){    
  88.                         var myRegEx  = /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/;    
  89.                         var isValid = myRegEx.test(value);    
  90.                         return isValid;    
  91.                     }    
  92.                 },    
  93.                 {    
  94.                     required: true,    
  95.                     selector: "#confirmPassword",    
  96.                     equalTo: "#createPassword",    
  97.                     onblur: true,    
  98.                 },                    
  99.                 {    
  100.                     required: true,    
  101.                     selector: "#igComboInterests",    
  102.                     onchange: true,    
  103.                     lengthRange: [2]    
  104.                 },    
  105.                 {    
  106.                     required: true,    
  107.                     required: true,    
  108.                     selector: "#igCheckboxAccept",    
  109.                     onchange: true    
  110.                 },    
  111.                 {    
  112.                     selector: "#igCheckboxSubscribe",    
  113.                     onchange: true    
  114.                 }    
  115.                 ]    
  116.             });    
  117.         });    
  118.     </script>   
Listing 13
 
The final output of the code will like Figure 6.
 
JavaScript
 Figure 6 
 

Conclusion

 
IGValidator provides an easy and simple way to implement data validations in HTML and web pages using JavaScript. It also helps to maintain a centralized method to validate the entire web page. In this article, I have demonstrated how to control IGValidator to validate various input controls on a web page.