This is an old blog. My new blog is moved here.

jQuery form validation JavaScript tutorial

3/23/2009

I know there are many similar plug-ins already written, but I was not able to find something that would give me the flexibility I needed, so here is another approach to do client side JavaScript validation using jQuery.

Ok, so lets start, First we need to define our own namespace. For the lack of creativity, let’s just call it DP.

//creates MRX namespace
var DP = (typeof DP == "object") ? DP : {};

Next, we will write our validation class. Notice that I am using private and public methods, to differentiate which methods are to be exposed and should be hidden from the outside.


DP.validateForm = function(){

    //generic check value method
    var fromReset = function(elmId, wrongValue, messageText){
        //reset
        $(".from_wrp input").css({"border":"1px solid #ACA69F"});
        $(".from_wrp select").css({"border":"1px solid #ACA69F"});
        $("#error_messages").empty("");
    }

    //generic check value method
    var valueCheck = function(elmId, wrongValue, messageText){
        if($("#" + elmId).val() == wrongValue){
            createAlert(elmId, messageText);
        }
    }
   
    //alert method
    var createAlert = function(elmId, messageText){
        $("#" + elmId).css({"border":"1px solid #f00"});
        //alert(messageText);
        $("#error_messages").append("" + messageText + ", ");
    }

    //zip validation
    var isZip = function(s){
        var reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
        if (!reZip.test(s)) {
            return false;
        }
        return true;
    }
   
    //checks if value is integer
    var isInt = function(n){
        var reInt = new RegExp(/^-?\d+$/);
        if (!reInt.test(n)) {
            return false;
        }
        return true;
    }
   
   
    //public method checks fieds
    //requires 'valSetting' setting object
    this.runCheck = function(){
        //reseet form
        fromReset();
        //run checks
        for (i=0;i<this.valSetting.fileds.length;i++){
           
            if(this.valSetting.fileds[i].type == "zip"){
                //zip check
                if(isZip($("#" + this.valSetting.fileds[i].id).val()) == false){   
                    createAlert(this.valSetting.fileds[i].id, this.valSetting.fileds[i].msg);
                }
            }
            else if (this.valSetting.fileds[i].type == "number"){
                //checks for number
                if(isInt($("#" + this.valSetting.fileds[i].id).val()) == false){   
                    createAlert(this.valSetting.fileds[i].id, this.valSetting.fileds[i].msg);
                }
            }
            else{
                //checks for value
                valueCheck(this.valSetting.fileds[i].id, this.valSetting.fileds[i].val, this.valSetting.fileds[i].msg);
            }
        }
    }

}

In this example, we can validate against specific value. In addition, we have options to validate a zip code or an email format. These special methods could be extended with other regular expression validates. This was by the way one of the form validation features, I that I was missing with already written jQuery plug-ins.

Finally, lets look what will the implementation look like. Let’s take a simple form that we need to validate. Each flied that we will validate, we will give an ID, and on the bottom, using inline JavaScript, we will create an instance of a our validation class, and create a settings objects.

<form id="form" class="popup_from_wrp">

    <label>First Name:</label>
    <input id="first_name" />   
                           
    <label>Last Name:</label>
    <input id="last_name" />
   
    <label>Address line:</label>   
    <input id="order_address" />
   
    <label>City:</label>
    <input id="order_city" />   
                               
    <label>Choose a State</label>
    <select id="order_state">
        <option>NY</option>
        <option></option>
    </select>       
   
    <label>Enter Zipcode</label>
    <input id="order_zip" />
   
    <label>Email address:</label>
    <input />                                   
   
    <span id="error_messages"></span>

    <script type="text/javascript">
   
    //creates instance of the validation class
    var vl = new DP.validateForm();
   
    //passes validation settings
    vl.valSetting = {fileds : [
        {id : "first_name", val : 0, msg : "First Name", type : ""},
        {id : "last_name", val : 0, msg : "Last Name", type : ""},
        {id : "order_address", val : 0, msg : "Address", type : ""},
        {id : "order_city", val : 0, msg : "City", type : ""},
        {id : "order_state", val : 0, msg : "State", type : ""},
        {id : "order_zip", val : 0, msg : "State", type : "zip"}
        }]
    };

    </script>
   
    <a href="#" onclick="vl.runCheck();">submit</a>               

</form>

Responses to The jquery form validation javascript tutorial

  1. Sam Says:
    Tuesday, March 24, 2009 2:31 AM
    Hi, I was curious how you felt about Jquery vs Prototype since you have worked with both? Do you prefer on over the other? What do you think the future holds with microsoft including Jquery in MVC 1.0? I have been using jquery for some basic tasks, but my wife found endless.com and liked the search functionality, especially the user experience. She would like me to use it on this one project I work on. After digging around I finally figured out it was done using prototype and then I found your blog post on endless and looked at your code example/implementation that you did using prototype and scriptaculous. Do you know any Jquery plugins that already operate like that?
  2. srivas Says:
    Thursday, April 16, 2009 1:16 AM
    hi devid,can please send me the jquery form validation tutorial
  3. WebTenet Solutions Says:
    Thursday, July 02, 2009 2:17 AM
    In your example code above, please see these two lines: //passes validation settings vl.valSetting = {fileds : [ I think there is a typo. "fileds" should be "fields". Also your comment form, the Name field if not filled shows "Please enter your website url!" as the message. Could you please correct it? Thanks.
  4. maxi Says:
    Friday, March 19, 2010 12:03 AM
    When u give any tutorial try to give all the supporting file...Else it is looks like fake..
  5. keith Says:
    Wednesday, March 24, 2010 12:28 PM
    is there a working demo of this?
  6. adarsh pandey Says:
    Thursday, February 18, 2010 3:59 AM
    send me jquery info.