Home arrow PHP arrow Page 5 - Building a PHP5 Form Processor: Coding the Form Validator Module

Checking for errors: defining the “checkErrors()” and displayErrors()” methods - PHP

In this second part of a three-part series, we take up the topic of server-side validation. By the time you finish this article, you'll have the general guidelines for how to build a form validating class. You'll use some PHP built-in introspection functions, along with regular expressions, to assist you in building this class.

TABLE OF CONTENTS:
  1. Building a PHP5 Form Processor: Coding the Form Validator Module
  2. Checking for empty and integer values: looking at the “validateEmpty()” and “validateInteger()” methods
  3. Testing numeric values and ranges: defining the “validateNumber()” and “validateRange()” methods
  4. The big challenge: checking email addresses with the “validateEmail()” method
  5. Checking for errors: defining the “checkErrors()” and displayErrors()” methods
By: Alejandro Gervasio
Rating: starstarstarstarstar / 13
January 23, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: