Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Lightweight JavaScript Validation Library

4.85/5 (16 votes)
14 Oct 2013MIT4 min read 26.9K   300  
A lightweight JavaScript library that helps to easily setup a variety of client side validations
Many libraries and APIs facilitate form validation, but I found that they lack an appropriate system to provide a variety of validation notifications to the user. The script in this article is an effort to implement something to address that issue.

Introduction

In almost every web application, JavaScript is being used to validate HTML form inputs from the client side. Normally, these validations are very basic ranging from validating required fields to email addresses and date fields, but for that, we have to write custom code to handle every different input and validation. This approach becomes even more difficult to manage when there are numerous inputs to validate on the page.

There are many libraries and APIs out there to facilitate form validation by writing minimum code and in most cases, they deliver what they promise but I found that they lack an appropriate system to provide a variety of validation notifications to the user. I wanted to implement something to address that and this script is the result of that effort.

Using the Code

Using this code is very easy, the downloadable zip file contains validateJS script file, a compressed script file (if you don't use a build process) and some free to use notification images of different sizes. With the default settings, you just need to initialize the library to add the various validators for your input form elements.

Follow these simple steps to setup client side validations using this code.

Step 1

Download the script file (you can use the free validation images that come along with the validateJS script or you can use your own).

Image 1

Step 2

Add your input element to the HTML page and set the attribute validatorName value to the name of the validator.

JavaScript
<label for="txtFirstName">First Name:</label>
<input id="txtFirstName" maxlength="20" validatorName="FirstName" /> 

Step 3

Add the validation notification 'div' element and set the attribute validator value to the name of the validator for which you want to show this notification.

JavaScript
<label for="txtFirstName">First Name:</label>
<input id="txtFirstName" maxlength="20" validatorName="FirstName" />
<div validator="FirstName"></div> 

Right now, there are three types of notifications that can be shown to the user: Image, Tooltip Messages and Background Highlight. All three of these can be turned on and off according to the requirement. The above div will act as a container for the notification icons.

Step 4

Initialize the library and add new validators.

JavaScript
$(document).ready(function () {
...
    vManager = new ValidationManager()
                .addValidator(["FirstName"], 
                [{ type: ValidationType.Required, message: "Please enter your first name." }
                ,{type: ValidationType.Alphabets, message: "Only alphabts are allowed here."}])
		.validateOnTextChange(true, SetDemoSummary)
                .highlightBackground(true)
                .initialize();
    //This function is not part of the syntax
    function SetDemoSummary() {
        var i = 0;
        var validationResults = null;
        var validationSummary = "";
        validationResults = vManager.getValidationResults();
        validationSummary += "<ul>";
        for (; i < validationResults.length; i++) {
            validationSummary += "<li style='padding:4px;'>";
            validationSummary += validationResults[i].message;
            validationSummary += "</li>";
        }
        validationSummary += "</ul>";
        $("#divFormSummary").html(validationSummary);
    } 

In the above code, first a new validation manager object is initialized. Two validators (Required and Alphabets) are then added to it using the .addValidator() function and after that, the object is initialized using the .initialize() function. The validation will fire on change event and validation summary will be created by automated calling of the function SetSummary(). The syntax of .addValidator() is explained as follows:

JavaScript
vManager = new ValidationManager()
    .addValidator([validatorName1, validatorName2,...], 
    [{ validation Rules 1 }, { validation Rules 2 },...])
    .initialize();    

where Validation Rules format = {type: Validation Type, rule: Validation Rule, message: Validation Message}

For a detailed description of the above syntax and other documentation, you'll have to visit this page.

Step 5

Fire validation(s) by using .validate() or .validateAll() functions of the ValidationManager object.

JavaScript
vManager.validate(["FirstName"]); 

Image 2

Right now, the following validation types are supported and can be used to validate a variety of inputs:

Required

This is the required field validator. It makes sure that the user must input some value or makes some selection.

Compare

This validation type compares the input value with the type of comparision rule provided.

Range

This validation type checks if the input value lies between the specified range or not.

RegularExpression

This validation type validates the input with the regular expression string provided.

Custom

This validation calls the provided function and passes the input control's value to that function as a parameter.

MinLength

This validation type validates that the input value's length is less than or equal to the minimum value.

MaxLength

This validation type validates that the input value's length is greater than or equal to the maximum value.

Alphabets

This validation type makes sure that the input consists of only alphabets and whitespace.

AlphaNumeric

This validation type makes sure that the input consists of only alphabets and numbers.

Numeric

This validation type makes sure that the input consists of only numbers.

You need to add a reference to the jQuery library before using this code as this library relies heavily on jQuery for cross browser compatibility. I have tried to make the implementation scalable to any number of validations that are required. Also, the code needs to update the DOM before firing any validations so you always need to call .initialize() method to setup the validation manager properly.

The default config points to static image resources and you can change that setting by calling the methods .setPassImage() and .setFailImage().

For complete documentation, visit the GitHub page for validateJS, you can also download the script from this page:

This code is under MIT so you can use it in any way you want. I would welcome any issues/bugs (log them here if you want to) and also helpful suggestions, or you can fork the code on GitHub and make changes that suit your requirement.

History

  • 15th October, 2013: Initial version

License

This article, along with any associated source code and files, is licensed under The MIT License