PHP
  Home arrow PHP arrow Page 3 - Building a PHP 5 Form Processor: Codin...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Building a PHP 5 Form Processor: Coding the Form Generator Module
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 26
    2006-01-16

    Table of Contents:
  • Building a PHP 5 Form Processor: Coding the Form Generator Module
  • Creating online forms: defining a reusable class for rendering form elements
  • Integrating client-side validation: defining the signature of the “JSGenerator” class
  • Constructing forms programmatically: defining the “formGenerator” class

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Building a PHP 5 Form Processor: Coding the Form Generator Module - Integrating client-side validation: defining the signature of the “JSGenerator” class


    (Page 3 of 4 )

    As I explained before, the “JSGenerator” class takes care of loading the basic JavaScript validation functions, as well as the dynamic generation of the JavaScript code that uses these functions. First, let me show you how this class is defined and then I’ll demonstrate how it works. Its definition is as follows:

    abstract class JSGenerator{
        private static $js=array();
        // load external JavaScript validating functions
        public function initializeFunctions(){
            self::$js['ext']='<script language="javascript"
    src="functions.js"></script>';
        }
        // add JavaScript validating function to selected field
        public function addValidation($fieldName,$valData){
            if(!is_array($valData)){
                throw new Exception('Invalid client-side validation
    array');
            }
            $obj='document.getElementsByTagName("form")[0].elements
    ["'.$fieldName.'"]';
            // obtain client-side validating function & error message
            list($valFunction,$errorMessage)=$valData;
            self::$js['int'].='if
    (!'.$valFunction.'('.$obj.',"'.$errorMessage.'")){'.$obj.'.focus
    ();return false};';
        }
        // return JavaScript code
        public function getCode(){
            return self::$js['ext'].'<script language="javascript">function validate(){'.self::$js['int'].'}
    </script>';
        }
    }

    Since I’ve already explained the reason for defining this class abstract, I’ll now focus on its job. As you can see, the class exposes only one static member, $js, which is declared by default as an array structure. This property will store first the whole set of JavaScript checking functions, and second the code responsible for calling these functions, in all the cases where form elements contain a “required” attribute.

    According to the concepts deployed above, the first method of the class, “initializeFunctions()” is tasked with loading the JavaScript functions that perform basic client-side validation. Here’s what it looks like:

    public function initializeFunctions(){
        self::$js['ext']='<script language="javascript"
    src="functions.js"></script>';
    }

    In this case, I’m utilizing an associative array to identify each fragment of JavaScript code, thus the self::$js[‘ext’] element points to the external functions, while self::$js[‘int’], references all the internal code generated for required form fields. To clarify this concept, take a look at the method shown below:

    public function addValidation($fieldName,$valData){
        if(!is_array($valData)){
            throw new Exception('Invalid client-side validation
    array');
        }
        $obj='document.getElementsByTagName("form")[0].elements
    ["'.$fieldName.'"]';
        // obtain client-side validating function & error message
        list($valFunction,$errorMessage)=$valData;
        self::$js['int'].='if
    (!'.$valFunction.'('.$obj.',"'.$errorMessage.'")){'.$obj.'.focus
    ();return false};';
    }

    The above method takes two incoming parameters: the name of the field being validated, along with the $valData array. As you’ll see right at the moment of setting up an example, this array will contain the name of the JavaScript function used to check the field, in conjunction with the warning message displayed when validating the field. Of course, before I leap forward to reviewing the last class method, here is the list for the basic checking JavaScript functions used within the class:

    function empty(obj,message){
        if(obj.value==''){
            alert(message);
            return false;
        }
        return true;
    }
    function int(obj,message){
        if(parseInt(obj.value)!=obj.value){
            alert(message);
            return false;
        }
        return true;
    }
    function email(obj,message){
        if(
    !/.+@.+\..+./.test(obj.value)){
            alert(message);
            return false;
        }
        return true;
    }
    if(document.getElementById&&document.createElement&&document.
    getElementsByTagName){
        document.getElementsByTagName('form')[0].onsubmit=function()
    {return validate()};
    }

    So these functions take care of basic client-side validation. As you may have guessed, it’s fairly easy to add new functions as per your specific requirements, but for the moment I’ll keep the client-side checking process limited to validating empty fields, integer values and email addresses.

    After the above functions have been loaded, the script will automatically invoke the “validate()” function when the form is submitted, so the checking functions in question can be conveniently utilized.

    At this stage, the only class method left to explain is “getCode()”. Essentially, when called, it returns the complete JavaScript code that first loads the global functions, and then performs validation on all the required form fields. Its definition is as follows:

    public function getCode(){
        return self::$js['ext'].'<script
    language="javascript">function validate(){'.self::$js['int'].'}
    </script>';
    }

    At this point, hopefully you understand how the “JSGenerator” class does its business, by generating the complete client-side validating code. Therefore, join me in the new few lines, to see how the two classes defined earlier can be used in the context of a third class, in order to programmatically construct online forms.

    More PHP Articles
    More By Alejandro Gervasio


       · The first article walks through the development of the different classes that...
       · Not that I'm lazy (just don't have the time right now), but is there a code archive...
       · I'd like to thank you for your kind comments on this article. I really appreciate...
       · Can you give some exmples of how to use these classes, please
       · Hello,Thanks for the feedback. If you want to see a full-featured example on how...
     

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT