Developing Jquery Form Validation Plugin
Introduction To Form Validation with Jquery
If you read my previous tutorial on validation, you will notice that we have to write validation code for each field. So we had huge amount of duplicate code. Look at the following example which validates 2 text fields to check if their value is empty.
Now you can see that 3 lines (if condition,setting error and alert user) is repeated for both fields. If we have large number of fields, we will have to write lot of duplicate code and also we will have to modify every line of code if we have to change the code for reqired validation. So this is a bad practice.
I have taught you to do validations manually in the previous tutorial. My intention was to show you how validations work at basic level. Since you are familiar with the basics, now you can use a validation plugin in your projects to enhance the reusability and quality of code.
Once you complete this tutorial you will be able to do the above validation with following code + validation plugin.
Now we have used the plugin as shown in above code. Since this is a small form with limited fields you want see the reduce in number of lines in the code. But the quality of the code is increased since now the required function is inside the validation plugin. What we are doing is calling the plugin function for every field. So if we want to change the required validation function, we just need to modify a single place inside validation plugin.
Also all the validation rules are called in one line instead of writing separate code for each type of validation. Now you can see the difference in using validation plugin over manual validation. Lets start to build the validation plugin from scratch.
Define the Plugin Structure
var error_count= 0; (function($) { $.innovative_form_validation= { defaults:{ validation_rules : '' }, init:function(validation_options) { }, requiredCheck:function() { }, minLengthCheck:function() { } }; })(jQuery);
(function($) { $.innovative_form_validation= { }; })(jQuery);
This is the basic structure of our plugin. innovative_form_validation is the name of our plugin. All the plugin code will be written inside the brackets of innovative_form_validation function.
(function($) { $.innovative_form_validation= { defaults:{ validation_rules : '' } }; })(jQuery);
- defaults variable will store the default variable values for our plugin. These values will be used when we don’t pass the variables to initialize function of plugin. Initialize function will be discussed later.
- In the above code I have defined single default variable. validation_rules is a default variable with empty value. You can define a default value according to your requirement.
(function($) { $.innovative_form_validation= { defaults:{ validation_rules : '' }, init:function(validation_options) { }, requiredCheck:function() { }, minLengthCheck:function() { } }; })(jQuery);
- After the default values you can insert functions separated by commas as shown above.
- init function will be used to initialize the plugin. variable called validation_options is passed to the init function.
- Plugin will extract the variables and values from variable_options and if values are not provided it will use the values of default variable.
Define Validation Rule Passing Structure
Now we have defined the structure of our plugin. Next thing we have to do is to define a structure for passing validation rules for each form field. I have used a json based structure for passing rules as shown in the following code.
var validation_rules = { "0": {"field_name":"fname", "field_value":fname, "rules": { "required":"", "maxlength":3} }, "1": {"field_name":"lname", "field_value":lname, "rules": { "required":"", "minlength":3} } };
- In the above code i have included all the validation rules inside a single json string. Numbers (0,1) defines the number of fields in the form.
- For a single form item there are 3 variables you have to define.
- field_name is the form element name
- field_value is the user entered value for the form field
- rules will define all the validation rules related to the function. It has multiple values as shown in the code above.
- Field 0 contains 2 validation rules called required and maxlength. required has a empty value and maxlength is defined as 3.
- You can add any number of rules according to the above syntax.
How To Display Validation Errors
- You can see that under every field I have defined a div element to display the error for that form field.
- Id of the div is constricted with id of the form field + “_error” suffix. Also the class of element is defined as iform-error.
Initializing Form Validation
Since we have defined all the structures for creating the plugin, lets move onto the init function of the plugin which will initialize all the form validations.
init:function(validation_options) { var options = $.extend($.innovative_form_validation.defaults, validation_options); error_count = 0; $('.iform-error').html(""); for(i in options.validation_rules){ var val_field_name = options.validation_rules[i].field_name; var val_field_value = options.validation_rules[i].field_value; var val_field_rules = options.validation_rules[i].rules; $.each(val_field_rules, function(k,v) { switch (k) { case 'required': $.innovative_form_validation.requiredCheck(val_field_name,val_field_value); break; } }); }
Above code contains complete code for init function of our plugin. Now lets take a look at what happens inside init function.
We have to pass the validation fields and constraints to the init function as a json string as mentioned in previous section. Then the follwoing line of code will extract the information on json string to options variable. If all the defined values are not available, it will use the values in default variable.
var options = $.extend($.innovative_form_validation.defaults, validation_options);
Once the variables are extracted we call the following line to remove all the errors previously displayed in error fields.
$('.iform-error').html("");
Now we can call our validation rules passed in the json string using the follwoing code snippet inside the init method.
for(i in options.validation_rules){ var val_field_name = options.validation_rules[i].field_name; var val_field_value = options.validation_rules[i].field_value; var val_field_rules = options.validation_rules[i].rules; $.each(val_field_rules, function(k,v) { switch (k) { case 'required': $.innovative_form_validation.requiredCheck(val_field_name,val_field_value); break; case 'numeric': $.innovative_form_validation.numericCheck(val_field_name,val_field_value); break; case 'minlength': $.innovative_form_validation.minLengthCheck(val_field_name,val_field_value,v); break; case 'maxlength': $.innovative_form_validation.maxLengthCheck(val_field_name,val_field_value,v); break; } }); }
- In this plugin we are only using a single variable called validation_rules in the init function. How to pass the validation_rules variable will be discussed later.
- First we have to traverse through each section of validation_rules variable. I have used a for loop for that as shown in above code.
- Then the next 3 lines of code will assign field_name,field_values and rules to the respective variables to make the usage easy.
- Then we can traverse through each validation rule using jquery each function.
- Inside the switch statement name of the validation rule will be checked and respective validation function will be called.
- Form Field name and field value will be passed to all the validation functions.
- Some validation functions such as minlength and maxlength needs a value to be checked against a given value. In such cases 3rd variable called check_value will be passed to the function.
- Finally we return the error count generated from various validation functions as discussed in the next section.
Adding Reusable Validation Functions
Now lets take a look at how we are going to create validation functions inside the plugin. You can add the validation functions right after the init function. Following code you how to create required validation function.
(function($) { $.innovative_form_validation= { defaults:{ validation_rules : '' }, init:function(validation_options) { }, requiredCheck:function(val_field_name,val_field_value) { if(val_field_value == ''){ $('#'+val_field_name+"_error").append("Cannot be empty
"); error_count++; } } }; })(jQuery);
- I have added a validation function for validating empty fields called requiredCheck right after the init function.
- Field name and field values are passed as variables to requiredCheck function.
- Then we check if the value is empty and assign the default error using the syntax we defined in the How To Display Validation Errors section.
- finally we increment the value of error variable to increase the error value
- Every time you insert a new validation function to the plugin you have also define a new case inside the switch statement as shown in the previous section
How To Use the Validation Plugin
Use the following code and save it in a js file called ivalidation.js.
var error_count= 0; (function($) { $.innovative_form_validation= { defaults:{ validation_rules : '' }, init:function(validation_options) { var options = $.extend($.innovative_form_validation.defaults, validation_options); error_count = 0; $('.iform-error').html(""); for(i in options.validation_rules){ var val_field_name = options.validation_rules[i].field_name; var val_field_value = options.validation_rules[i].field_value; var val_field_rules = options.validation_rules[i].rules; $.each(val_field_rules, function(k,v) { switch (k) { case 'required': $.innovative_form_validation.requiredCheck(val_field_name,val_field_value); break; } }); } return error_count; }, requiredCheck:function(val_field_name,val_field_value) { if(val_field_value == ''){ $('#'+val_field_name+"_error").append("Cannot be empty
"); error_count++; } } }; })(jQuery);
Create elements in json string for every form item you want to validate using the following type of code.
var fname = $('#fname').val(); var lname = $('#lname').val(); var validation_rules = { "0": {"field_name":"fname", "field_value":fname, "rules": { "required":"", "maxlength":3} }, "1": {"field_name":"lname", "field_value":lname, "rules": { "required":"", "minlength":3} } };
In the above example i have defined validation rules for 2 form fields.
Use the following code inside the form submit function ti initialize the ivalidation plugin.
var validation_status = $.innovative_form_validation.init({ validation_rules : validation_rules });
Error count will be returned to the validation_status variable. If the value is not 0 you have to stop the form submission.
Leave a Reply