JavaScript · Programming

A sample jQuery plugin

An example of a simple jQuery plugin that does some basic form validation.

The HTML

The HTML is a simple one with just three form fields.

<form id="prod_form" method="get" action="#"> 
    <label for="prod-name">Product Name* :</label>
    <input type="text" name="prod-name" id="prod-name"/>
    <span class="error" id="prod-name-error"></span><br/> 
    <br/> 
     
    <label for="prod-quant">Product Quant* :</label>
    <input type="text" name="prod-quant" id="prod-quant"/> 
    <span class="error" id="prod-quant-error"></span>
    <br/> 
    
    <label for="email">E-mail ID* :</label>
    <input type="text" name="email" id="email"/> 
    <span class="error" id="email-error"></span>
    <br/> 
    
    <label for="dob" title="date of birth">DOB* :</label>
    <input type="text" name="dob" id="dob"/> 
    <span class="error" id="dob-error"></span>
    <br/> 
    
    <input type="submit" value='Submit'/> 
</form>


Create Plugin
Now we will create the jQuery plugin with multiple methods to check the input and validate it. The plugin will be stored in a separate JavaScript file called validate.js.

//demo jquery plugin
(
    function($) {
        
        $.fn.validate = function(options) {
            //method for email validation
            function emailValidate(email) {
                var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                
                if(reg.test(email) === false) {
                    return false;
                }
                
                return true;
            }
            
            //method for date of birth validation
            function dobValidate(date) {
                
                if(date == '')
                    return false;
                
                    var d = Date.parse(date); //format July 20, 2011
                    
                    if(isNaN(d))
                        return false;
                    
                    var cd = new Date();
                    
                    if((cd - d) < 0) {
                        return false;
                    }
                
                return true;
            }
            
            //method for empty field validation
            function emptyValidate(data) {
                
                if($.trim(data) === '') {
                    return false;
                }
                
                return true;
            }
            
            //loop through each form
            return this.each(function() {

                //bind the form's onSubmit event to do validation
                $(this).bind('submit',null,function() {
                
                    var isValid = true;
                    
                    //for each text field in the for perform validation
                    $(this).children('input[type=text]').each(function() {
                        var data = $(this).val();
                        var errorSpan = $('#'+$(this).attr('id')+'-error');
                        //check empty
                        if (!emptyValidate(data)) {
                            errorSpan.show().text('Error no product name entered');
                            isValid = false;
                        } else {
                            errorSpan.hide();
                        }
                        //check email
                        if($(this).attr('id').indexOf('email') != -1) {
                            if(!emailValidate(data)) {
                                errorSpan.show().text('Wrong email');
                                isValid = false;
                            } else {
                                errorSpan.hide();
                            }
                        }
                        //check date of birth
                        if($(this).attr('id').indexOf('dob') != -1) {
                            if(!dobValidate(data)) {
                                errorSpan.show().text('Wrong DOB');
                                isValid = false;
                            } else {
                                errorSpan.hide();
                            }
                        }
                        
                    });
                    //return false if form validation fails, this is needed to 
                    //prevent default action
                    return isValid;    
                    
                });
                
            });    
            
        }    
        
    }
)(jQuery);

Including jQuery
Include the jQuery library in your page in the head tag or before the closing body tag.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

Including Plugin
Include you plugin AFTER you have included the jQuery library.

<script src="/YOUR_JS_LOCATION/validate.js"></script>

Call the jQuery plugin

Call the jQuery plugin AFTER you have included the plugin and jQuery library.

<script type="text/javascript">
    $(document).ready(function(){ 
        $('#prod_form').validate();
    });
</script>

Full HTML Source

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Test Form Input jQuery plugin</title>
    </head>
    <body>
        <form id="prod_form" method="get" action="#"> 
            <label for="prod-name">Product Name* :</label><input type="text" name="prod-name" id="prod-name"/>
            <span class="error" id="prod-name-error"></span><br/> 
            <br/> 
             
            <label for="prod-quant">Product Quant* :</label><input type="text" name="prod-quant" id="prod-quant"/> 
            <span class="error" id="prod-quant-error"></span>
            <br/> 
            
            <label for="email">E-mail ID* :</label><input type="text" name="email" id="email"/> 
            <span class="error" id="email-error"></span>
            <br/> 
            
            <label for="dob" title="date of birth">DOB* :</label><input type="text" name="dob" id="dob"/> 
            <span class="error" id="dob-error"></span>
            <br/> 
            
            <input type="submit" value='Submit'/> 
        </form>
        <script src="/js/validate-form.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){ 
                $('#prod_form').validate();
            });
        </script>
</body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s