Wednesday, September 18, 2013

Dynamically validating input using java script in php code igniter

This is to simply validate input while you are typing in php/html using java script. I have tried this in Code Igniter framework with netbeans IDE 7.3 also.
As an example we will see how to validate a text box where only  positive numbers are allowed including zero. Later you can customize this code according to your requirements

Your html code for text box will look like this

<input type="text"  class="form_text" id="marks" name="marks" onkeyup="validatePositiveNumber(this.value,'errorMarks')"/>
                     <br/> <span id="errorMarks"></span>

here text box id name is "marks". you can give any name you like
I have used a span to display the error message. Its id is "errorMarks" where you can give any name

We need to use "onkeyup" event of the text box as we intend to validate its value each and every time user presses some key. I have given the function name as "validatePositiveNumber" which I'm going to write using javascript. The function takes 2 parameters current value of the text box(this.value) and span id to display the error message ("errorMarks")

Now it's time to create javascript. You can include following javascript inside head section or inside the same form as the text box

 <script>
            function isFloat(input)
            { 
                //to check float values. It checks each character

                var i;
                var j=0;//to count number of decimal points in the parameter

                for (i = 0; i < input.length; i++)
                {
                    // Check that current character is a digit(0-9) or dot
                    var c = input.charAt(i);
  
                    if (((c < "0") || (c > "9")))
                    {
                        if(c != ".")
                        {
                           //if it's not a digit or not "." return false
                            return false;
                        } 
                        else        
                        {
                             //if it's "." counting number of decimal points 
                            j++;
                        }     
                    }//end of if()
   
                }//end of for()

                // if all characters are digits n dots then make sure it has at most one decimal point.
                if(j>1)
                {
                    return false;
                }
                return true;
             
                //end of function isFloat()
            }


            function validatePositiveNumber(str,id)
            {
                // check whether it's empty
                if (str.length==0)
                {
                    document.getElementById(id).style.color = 'red';//error font color
                    document.getElementById(id).innerHTML="Please Enter the Value";//error message
                    return false;
        
                } 
                else if (!isFloat(str) || str.indexOf(".") == (str.length-1))
                {
                   //check whether it s not a positive float or containing decimal point at the very end

                    document.getElementById(id).style.color = 'red';//error font color
                    document.getElementById(id).innerHTML="Please Enter a valid value";//error message
                    return false;
                }
                else
                {
                    // when it's valid showing no error messages at all
                    document.getElementById(id).innerHTML="";
                    return true;
                }
                //end of function
            }
        </script>

That's it................Enjoy :)

Output immediately after you enter an invalid character 

Output immediately after you enter tab key and skip the text box

Further Reference :
on key events: http://www.w3schools.com/jsref/event_onkeypress.asp
more events:http://www.w3schools.com/jsref/dom_obj_event.asp


Code credit : I got this javascript code from one of my friends Mushthaq Rumy with little modifications
Hope it will be useful for you.

6 comments:

  1. Your tone is so friendly. Can understand the content in a clear manner.
    Thx
    Good Article !!

    ReplyDelete
    Replies
    1. Thanks Nohim Ys for the compliment. It encourages me alot.

      Delete
  2. A beautiful way of expressing a complex code work. Really understandable. Enjoyed the posting....

    ReplyDelete
  3. Thanks for giving credits....!!! anyway Lovely blog...!! very understandable..! Keep up the good work.. :)

    ReplyDelete
  4. Thank you Mushthaq Rumy!!!. It encourages me alot... :)

    ReplyDelete