jQuery Form Validation Plugin: Documentation and Demos

NOTE: No JavaScript/front end form validation solution is foolproof. It is, at best, a convenience that should never be relied on to ensure security/data validity. Always implement server side validation to complement front end validation.

Overview (click here to jump down to the demos)

This plugin provides a convenient means to implement validation on common HTML input fields. It supports validating any input element that supports the use of the jQuery $('#element_id').val(); or $('#element_id).is(':checked'); methods. The plugin supports unicode text, including emails that use unicode characters.

Getting Started

Adding The Plugin to Your Page.

Add something like the following to your HTML pages:

<script src="js/jquery.min.js"></script>
<script src="js/validation.min.js"></script>

Required tag attributes and classes

In order to use the plugin, you must supply certain attributes and classes in your form tags.

Required CSS Class: validate; Rquired tag attribute: id

All form input tags must include the CSS class validate to indicate to the plugin that it should validate this tag. At minimum, the validate tag will check if an input value is empty and display an error. You must also provide an id attribute that is unique from all other input ids so that the plugin can distinguish the input being validated from other inputs.

Ex: <input type="text" name="my_input" id="my_input" class="validate" ... >

Optional CSS Classes: allow-empty check-length, check-email, check-match, numbers-only, letters-only, alphanumeric-only, is-checked

allow-empty

This is an improvement on the required tag attribute as it relates to form validation. Using the CSS class allow-empty tells the plugin to validate the field if there is user input, but flag it as having passed validation if there is no input. If the field is required, then simply adding validate covers that, no required attribute needed, and if the field is optional but you do want to validate the user input if a user decides to fill it in, then validate allow-empty takes care of that. This plugin assumes, rightly I think, that any form input you would want to validate would likely be required and it makes more sense to identify the presumably far fewer fields that are NOT required with allow-empty.

check-length

Checks the length of the input string. Requires at least one of the following data attributes data-validation-length-min and/or data-validation-length-max.

Ex: <input type="text" name="my_input" id="my_input" class="validate check-length" data-validation-length-min="10" data-validation-length-max="100" ... >

check-email

Checks for a valid email address. Supports unicode character emails. For example, an email like this 伊昭傑@郵件.商務 is valid and will pass validation.

Ex: <input type="text" name="email" id="email" class="validate check-email" ... >

check-match

Checks whether the value of two inputs match. You must add the data attribute data-validation-match to one of the tags to be matched. The value of data-validation-match must be the CSS id of the other input to be matched.

Ex: <input type="password" name="password" id="password" class="validate" ... >
<input type="password" name="verify_password" id="verify_password" class="validate check-match" data-validation-match="password" ... >

numbers-only

Checks if the user input is only numbers. Supports the use of the optional classes allow-spaces which permits numbers and spaces and allow-special-characters which permits the following characters often associated with formatted numbers: - / , . ( )

Ex: <input type="text" name="phone_number" id="phone_number" class="validate numbers-only allow-spaces allow-special-characters" ... >

letters-only

Checks if the user input is only letters. Supports the use of the optional classes allow-spaces which permits letters and spaces and allow-special-characters which permits all unicode letters as well as the following characters often found in first and last names: ' - _

Ex: <input type="text" name="your_name" id="your_name" class="validate letters-only allow-spaces allow-special-characters" ... >

alphanumeric-only

Checks if the user input is only alphanumeric characters. Supports all unicode alphabet characters by default. Supports the use of the optional class allow-spaces which permits alphanumeric characters and spaces.

Ex: <input type="text" name="your_address" id="your_address" class="validate alphanumeric-only allow-spaces" ... >

is-checked

Checks if a checkbox is checked.

Ex. <input type="checkbox" name="confirm" id="confirm" class="validate is-checked" ... >

Multiple Tests on One Input

It's very simple to perform multiple tests on a single input. Simply add the CSS classes associated with the tests you want to perform as well as the relevant data attributes.

Ex: <input type="text" name="us_zip_code" id="us_zip_code" class="validate numbers-only check-length" data-validation-length-min="5" data-validation-length-max="5" ... >

Displaying Messages

Required HTML element for displaying messages

You must provide one of these elements for every input tag you wish to validate. The ID of each message element must be exactly the same as the ID of the corresponding input element, but with the suffix -message. So, if your input tag has an ID of email_address, the ID of the message element must be email_address-message

<div id="email_address-message" class="error-message hidden"></div>

Required CSS Classes for Displaying Messages.

error-alert

This CSS class is added to the input element and changes the appearance of the element to inform the user that attention to this element is needed.

.error-alert {
    border: #a94442 solid 1px;
}

correct-alert

This CSS class is added to the input element only if the alertIfCorrect flag has been set when binding the plugin to an HTML form or a container element. It changes the appearance of the element to inform the user that they have entered information into the input element correctly.

.correct-alert {
    border: #5cb85c solid 1px;
}

error-message

This CSS class should style the message element when it becomes visible on an error. Here is an example style for this class:

.error-message {
    color: #a94442;
    font-weight: bold;
}

hidden

This CSS class will hide the message element. The plugin hides and shows the error message by adding and removing this class from a message element. If you are using Bootstrap, there already is a hidden CSS class. If you need to create your own, here is an example:

.hidden {
    display: none !important;
}

Methods of Displaying a Validation Message

Method 1: Putting the message inside the message element

<input type="text" name="your_name" id="your_name" class="validate">
<div id="your_name-message" class="error-message hidden">You must enter your name.</div>

Method 2: Using The data-error-message Attribute

<input type="text" name="your_name" id="your_name" class="validate" data-error-message="You must enter your name.">
<div id="your_name-message" class="error-message hidden"></div>

Binding the Plugin

To enable the validation plugin, you must call a plugin method to bind it to either an HTML form or a container element that contains a collection of input elements.

Binding to a Form

Bind to an HTML form with the ID submit-this-form

<script>
var flagIfCorrect = true; // Add the correct-alert class to a correctly filled input element.

$.validation.bindOnSubmit('submit-this-form', flagIfCorrect);
</script>

Binding to a Container

Bind to an HTML container with the ID form_container

<script>
var flagIfCorrect = true; // Add the correct-alert class to a correctly filled input element.
var returnClass = 'my-class'; // When you have a form where all fields are not validated, but you would like
                              // the the form to submit when a user presses return in one of these non-required inputs.
var callbackFunction = function () { console.log('Hello dere!'); } // A function for submitting the form or whatever
                                                                   // callback you prefer.
var functionArgs = ['arg1','arg2']; // An argument for the callback function. Need more than one argument?
                                    // Make the argument an array and process that array as arguments from
                                    // within your function.

// Catch when a user hits the return key in an input field.
$.validation.bindOnReturn('form_container', flagIfCorrect, returnClass, callbackFunction, functionArgs);


var formEvent = 'click'; // click, submit, etc.
var eventElementId = 'submit_form'; // In this case, we're listening for a click event on a button with the ID submit_form

// Catch the submit button click and call submit function
$.validation.bind('form_container', 'click', 'submit_form', flagIfCorrect, callbackFunction, functionArgs);
</script>

Plugin Properties

There is one useful plugin property that you can use in your on scripts to check if validation has been run on the form and if the inputs passed validation.

$.validation.passed

Contains a boolean value. Boolean true if validation ran and all inputs passed validation, boolean false if not.

Example usage:

if ($.validation.passed) {
   // do something
}
            

jQuery Form Validation Plugin: Usage Examples

Standard Form

<form name="sample_form" action="#" method="post" id="sample_form">
    <div>

        <input type="text" name="your_name" id="your_name" placeholder="Enter your name."
        class="validate letters-only allow-spaces check-length"
        data-validation-length-min="3" data-validation-length-max="100">

        <div id="your_name-message" class="error-message hidden">You must enter a name between 3 and 100 characters.</div>

    </div>
    <div>

        <input type="text" name="email" id="email" placeholder="Enter your email."
        class="validate check-email" data-error-message="You must enter a valid email address.">

        <div id="email-message" class="error-message hidden"></div>

    </div>
    <div>

        <input type="checkbox" name="my_checkbox" id="my_checkbox"
        class="validate is-checked" data-error-message="This box must be checked.">

         <div id="my_checkbox-message" class="error-message hidden"></div> Check this box.

    </div>

    <button type="submit" name="form_submit" id="form_submit">Submit</button>
</form>

<script>$.validation.bindOnSubmit('sample_form', true);</script>
            

Standard Form Demo

Check this box.

JavaScript Form

<div id="form_container">
    <div>
    
    <input type="text" name="your_email" id="your_email" placeholder="Enter your email."
        class="validate check-email" data-error-message="You must enter a valid email address.">
    
    <div id="your_email-message" class="error-message hidden"></div>
    
    </div>
    <div>

    <input type="text" name="alt_email" id="alt_email" placeholder="OPTIONAL: Enter an alternate email address"
        class="validate allow-empty check-email" data-error-message="You must enter a valid email address.">

    <div id="alt_email-message" class="error-message hidden"></div>

    </div>
    <div>
    
    <input type="password" name="your_password" id="your_password"
        placeholder="Enter your password." class="validate check-length" data-validation-length-min="8"
        data-error-message="You must enter a password that is at least 8 characters long.">
    
    <div id="your_password-message" class="error-message hidden"></div>
    
    </div>
    <div>

        <input type="password" name="your_password_match" id="your_password_match"
        placeholder="Repeat your password." class="validate check-match" data-validation-match="your_password"
        data-error-message="Passwords do not match">

        <div id="your_password_match-message" class="error-message hidden"></div>

    </div>
    <div>
    
    <select name="select_stuff" id="select_stuff" class="validate"
        data-error-message="You must select something!">
        <option value="">Select something</option>
        <option value="stuff">Stuff</option>
        <option value="things">Things</option>
    </select>
        
    <div id="select_stuff-message" class="error-message hidden"></div>
    
    </div>
    <div>
    <button type="button" name="submit_form" id="submit_form">Submit</button>
    </div>
</div>

<script>
// Will execute callback function when user presses return in an input field.
$.validation.bindOnReturn('form_container', true, null, submitForm);

// Catch the submit button click and call submit function
$.validation.bind('form_container', 'click', 'submit_form', true, submitForm);

function submitForm() {
    // put your Ajax POST code here.
    
    // make sure that the validation plugin ran and the form passed the tests
    if ($.validation.passed) {
        var email = $('#your_email').val();
        var password = $('#your_password').val();
        var stuff = $('#select_stuff').val();
        alert('Form passed validation! Values: '+email+':'+password+':'+stuff);
    }
}
</script>
            

JavaScript Form Demo