PHP
  Home arrow PHP arrow Page 5 - Building a PHP5 Form Processor: Coding the Form Validator Module
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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 PHP5 Form Processor: Coding the Form Validator Module
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 12
    2006-01-23


    Table of Contents:
  • Building a PHP5 Form Processor: Coding the Form Validator Module
  • Checking for empty and integer values: looking at the “validateEmpty()” and “validateInteger()” methods
  • Testing numeric values and ranges: defining the “validateNumber()” and “validateRange()” methods
  • The big challenge: checking email addresses with the “validateEmail()” method
  • Checking for errors: defining the “checkErrors()” and displayErrors()” methods

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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 PHP5 Form Processor: Coding the Form Validator Module - Checking for errors: defining the “checkErrors()” and displayErrors()” methods
    ( Page 5 of 5 )

    In order to determine whether any errors occurred during the form validation process, the class exposes the “checkErrors()” method, defined like this:

    public function checkErrors(){
        if(count($this->errors)>0){
            return true;
        }
        return false;
    }

    As you can see, the above method implements a simple wrapper for counting the number of elements in the $errors array. If this array isn’t empty, it means that one or more error messages were stored as new elements, and consequently failures occurred during the form validation. According to this condition, the method will return either true or false, reducing the error checking process to simply verify the Boolean flag returned when the method is invoked.

    Finally, the “displayErrors()” method is responsible for displaying all the error messages added during the form validation process. Its definition is as follows:

    public function displayErrors(){
        $errorOutput='<ul>';
        foreach($this->errors as $err){
            $errorOutput.='<li>'.$err.'</li>';
        }
        $errorOutput.='</ul>';
        return $errorOutput;
    }

    Here, the method listed above iterates over the $errors array and returns the corresponding error messages as an (X)HTML list, which is useful for displaying the appropriate warnings after the form has been submitted. In this case, I’ve opted to return the error output as a list of elements, but this can be easily changed to outputting errors in a different format.

    At this stage, with all the methods of the “formValidator” class defined and explained in detail, it’s time to show the complete source code for the pertinent class, so you can have an accurate idea of how it looks. Its definition is as follows:

    class formValidator{
        private $errors=array();
        public function __construct(){}
        // validate empty field
        public function validateEmpty
    ($field,$errorMessage,$min=4,$max=32){
            if(!isset($_POST[$field])||trim($_POST[$field])
    ==''||strlen($_POST[$field])<$min||strlen($_POST[$field])>$max){
                $this->errors[]=$errorMessage;
            }
        }
        // validate integer field
        public function validateInt($field,$errorMessage){
            if(!isset($_POST[$field])||!is_numeric($_POST[$field])
    ||intval($_POST[$field])!=$_POST[$field]){
                $this->errors[]=$errorMessage;
            }
        }
        // validate numeric field
        public function validateNumber($field,$errorMessage){
            if(!isset($_POST[$field])||!is_numeric($_POST[$field])){
                $this->errors[]=$errorMessage;
            }
        }
        // validate if field is within a range
        public function validateRange($field,$errorMessage,$min=1,$max=99){
            if(!isset($_POST[$field])||$_POST[$field]<$min||$_POST
    [$field]>$max){
                $this->errors[]=$errorMessage;
            }
        }
        // validate alphabetic field
        public function validateAlphabetic($field,$errorMessage){
            if(!isset($_POST[$field])||!preg_match("/^[a-zA-Z]
    +$/",$_POST[$field])){
                $this->errors[]=$errorMessage;
            }
        }
        // validate alphanumeric field
        public function validateAlphanum($field,$errorMessage){
            if(!isset($_POST[$field])||!preg_match("/^[a-zA-Z0-9]
    +$/",$_POST[$field])){
                $this->errors[]=$errorMessage;
            }
        }
        // validate email
        public function validateEmail($field,$errorMessage){
            if(!isset($_POST[$field])||!preg_match
    ("
    /.+@.+\..+./",$_POST[$field])||!checkdnsrr(array_pop(explode
    ("@",$_POST[$field])),"MX
    ")){
                $this->errors[]=$errorMessage;
            }
        }
        // check for errors
        public function checkErrors(){
            if(count($this->errors)>0){
                return true;
            }
            return false;
        }
        // return errors
        public function displayErrors(){
            $errorOutput='<ul>';
            foreach($this->errors as $err){
                $errorOutput.='<li>'.$err.'</li>';
            }
            $errorOutput.='</ul>';
            return $errorOutput;
        }
    }

    Tired of reading? Fine, just bear with me and read the last part of the article. It’s really worth it.

    Wrapping up

    Right, we’re done for now. Over this second article, I focused all my effort on developing the form “validator” module, which composes the second half of the PHP 5 form processor as I originally designed it. For this reason, I built an extendable form validating class, by defining some useful data checking methods, in order to provide the application with the ability to perform server-side form validation. Hopefully, this tutorial has been instructive for those developers wanting to implement an object-oriented solution for validating online forms with no hassles.

    Over the last part of the series, I’ll put all the classes to work together, as part of a full-featured example aimed at demonstrating the powerful capabilities of the form processor package. See you in the last tutorial!



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





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