Building a PHP5 Form Processor: Coding the Form Validator Module

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.

Introduction

This is the second part of the series “Building a PHP 5 form processor.” Welcome back. In the first article, I demonstrated how to programmatically construct online forms, in conjunction with the implementation of basic client-side validation. For this reason, I used some extensible PHP 5 classes. This turns the whole form generation process into a straightforward task, which comes in very handy when at least rough client-side verification is first performed on user input, and then server-side validation is applied before processing the data in some way.

The benefits of having a bunch of classes that do the hard work for constructing web forms rests on the ease of rendering form elements and building their proper layout. You need only use some lines of readable code; you do not need to deal specifically with the form’s (X)HTML markup or JavaScript functions responsible for performing data validation. This situation introduces a greater level of abstraction when building forms, something nearly impossible to achieve with traditional form development methods.

However, at the time of writing this series, I established that server-side validation would be an important part of the generic form processor package. Keeping this idea in mind, the second part of this series will be directed to developing a PHP 5 form verification class, which can be easily extended and improved either by modifying its existing checking methods or adding additional ones, in order to meet the requirements of a given web application.

Hopefully, by the end of this tutorial, you’ll have the general guidelines for how to build a form validating class, by utilizing some PHP built-in introspection functions, along with the functionality of regular expressions.

Want to know more about developing the form “validator” module? Right, stick with me and start reading!

Basic server-side validation: the barebones of a PHP 5 form validation class

Before any attempt to write the form “validator” class, first allow me to explain the driving logic hidden behind its structure. Essentially, the class will expose some basic methods for validating form data, ranging from checking for empty fields to more complex data validation, such as verifying email addresses. In addition, I’ll provide the class with the ability to validate alphabetic and alphanumeric data, float and integer values, and finally whether data is within a specific range of values. Of course, since these methods are only a small piece of the data validation terrain, you can write your own checking methods and extend the capabilities of the class, so it can be used in production environments.

Now that you know how the class will work, take a look at its structure:

class formValidator{
    private $errors=array();
    public function __construct(){}
    // validate empty field
    public function validateEmpty
($field,$errorMessage,$min=4,$max=32){
    }
    // validate integer field
    public function validateInt($field,$errorMessage){
    }
    // validate numeric field
    public function validateNumber($field,$errorMessage){
    }
    // validate if field is within a range
    public function validateRange
($field,$errorMessage,$min=1,$max=99){
    }
    // validate alphabetic field
    public function validateAlphabetic($field,$errorMessage){
    }
    // validate alphanumeric field
    public function validateAlphanum($field,$errorMessage){
    }
    // validate email
    public function validateEmail($field,$errorMessage){
    }
    // check for errors
    public function checkErrors(){
    }
    // return errors
    public function displayErrors(){
    }
}

As you can see, the structure of the above class shows how it will operate. Originally, the class will expose only one private property, $errors, defined by default as an array structure. As you may have guessed, this property will store the error messages corresponding to each offending field that doesn’t meet the validation rules. Aside from this property, I’ve defined the constructor as an empty method (certainly, you may want to completely remove it from the class). Eventually, it might be tasked with some initializing process, so I’ll keep it that way for now.

With reference to the validation methods in question, all of them will accept basically two arguments: the name of the form field to be verified, along with the appropriate error message to be displayed. As I said earlier, I’ve defined a few methods for validating empty values, integers, alphanumeric data and so forth, but the versatility of the class allows you to easily add more methods, such a those aimed at checking for URLs, IP addresses, postal codes, and so on.

Having described the data checking methods originally exposed by the class, there are a couple of methods that remain to be discussed. The first one, “checkErrors()” will be responsible for iterating over the $errors array, determining the existence (or not) of offending form fields. Finally, the “displayErrors()”, as it suggests, will return all the error messages stored in the $errors array to be properly displayed.

At this stage, I’m sure you can imagine at least the basic logic that will implement the corresponding validation methods, so it’s time to leap forward and explicitly define the signatures for each of them.

{mospagebreak title=Checking for empty and integer values: looking at the “validateEmpty()” and “validateInteger()” methods}

My round trip for defining the checking methods of the class begins with the specific implementation of the “validateEmpty()” method, which can be used to quickly check whether a form field is empty or not. Below is the pertinent method definition:

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;
    }
}

While the above method performs a rather trivial checking process, such as validating empty fields, it’s worth examining in detail, since all the subsequent methods will stick to a similar approach.

As you’ve seen, this method is called with two arguments: the name of the form field to be tested, and the error message to be displayed in case the field is found to be empty. Besides the mandatory parameters, the method takes two additional arguments defined with default values, $min and $max. These arguments come in hand for checking whether values are within a given length of characters.

Now, by returning to the validation process itself, notice how the PHP $_POST array is used internally, in order to access form variables. In this case, I’ve purposely utilized this PHP proprietary array, simply because I’m assuming that the form will use this request method. However, if you’re going to build your forms by using a specific request method, you may want to either hard code the proper $_POST /$_GET array for accessing form variables, or (a much better approximation) write a class method for obtaining the method used on the form.

With reference to this method, if the field is empty, then the corresponding error message passed in as an argument is stored as a new element in the $errors array, so it can be accessed at a later time, after the form has been submitted.

Since all of the checking process is extremely easy to follow, and the mechanism for storing error messages consists of a simple array, I can move forward to explain another validation method. In particular, this one is responsible for verifying whether a field contains an integer value. Its signature is listed below:

public function validateInt($field,$errorMessage){
    if(!isset($_POST[$field])||!is_numeric($_POST[$field])
||intval($_POST[$field])!=$_POST[$field]){
        $this->errors[]=$errorMessage;
    }
}

As you can appreciate, the above method looks a little more interesting. In short, it will test whether the value entered in the field is an integer. In order to check for this condition, the method uses the powerful combination of the “is_numeric()” and “intval()” PHP functions respectively. As with the first method, if the value entered isn’t an integer, the appropriate error message is added as a new element to the $errors array. Simple and efficient.

Now that you have a general idea of how most of the class methods work, it’s time to move on and define a few more methods. These are useful for testing whether the data is within a given range of numeric values, and eventually whether it’s numeric or not. So, scroll down the page and keep reading.

{mospagebreak title=Testing numeric values and ranges: defining the “validateNumber()” and “validateRange()” methods}

Indeed, another useful method to determine whether an user has entered a numeric value or not, is the “validateNumber()” method. Closely similar to the methods defined earlier, its source code looks like this:

public function validateNumber($field,$errorMessage){
    if(!isset($_POST[$field])||!is_numeric($_POST[$field])){
        $this->errors[]=$errorMessage;
    }
}

In this case the method will check if the value entered is a numeric string and accordingly store the appropriate error message in the $errors array. Despite its simplicity, I’ve found myself very often using this method on forms where only numeric values are allowed.

Now, take a look at another handy method, “validateRange()”, which can be very useful for checking if the value entered on a field is within a range of pre-defined boundaries. Its definition is listed below:

public function validateRange
($field,$errorMessage,$min=1,$max=99){
    if(!isset($_POST[$field])||$_POST[$field]<$min||$_POST
[$field]>$max){
        $this->errors[]=$errorMessage;
    }
}

 

Right, admittedly this method is very simple, so I won’t stop long on it. The only thing worthwhile of being denoted is the assignation of default values for the corresponding boundaries, which can be easily changed, in order to meet different validation requirements.

In a similar fashion, if the input supplied by an user is out of the given boundaries, an error message will be added as a new element of the $errors array. As you can see, adding more validation methods to the class is just a matter of writing the appropriate checking routines and storing error messages according to the type of test performed on the input data.

Having defined the methods responsible for checking numeric strings and ranges of values entered on forms, the next thing to be done is writing a couple more, so the class can be capable of validating alphabetic and alphanumeric strings.

Validating alphanumeric and alphabetic values: defining the “validateAlphabetic()” and “validateAlphanum()” methods

Checking for alphabetic and alphanumeric characters is really a straightforward task that can be easily performed by utilizing PHP regular expressions. Moreover, if you’ve been working with regular expressions for a while, you’ll realize that writing more methods to validate input that must meet a particular format is a breeze. Verifying postal codes or phone numbers is reduced to coding the corresponding string pattern. Based on this ability, the two methods listed below verify alphabetic and alphanumeric characters in input strings:

public function validateAlphabetic($field,$errorMessage){
    if(!isset($_POST[$field])||!preg_match(“/^[a-zA-Z]+$/”,$_POST
[$field])){
        $this->errors[]=$errorMessage;
    }
}

public function validateAlphanum($field,$errorMessage){
    if(!isset($_POST[$field])||!preg_match(“/^[a-zA-Z0-9]
+$/”,$_POST[$field])){
        $this->errors[]=$errorMessage;
    }
}

Definitely you’ll agree that these methods are simple to code and read. This ability to use regular expressions to validate user input comes in particularly handy, since it’s possible to encode complex string patterns and perform strict validation on user-supplied data. As you can see, the above listed methods demonstrate this concept, by encoding simple string patterns in order to check for alphabetic and alphanumeric characters in input data. In both cases, if the input string fails the test, the respective error messages are stored in the $errors array, as shown in previous class methods.

Certainly, I could spend more time coding additional methods to check whether input data fits a particular format. Since this process is reduced to tweaking string patterns in regular expressions, however, I won’t waste your precious time writing boring expressions. Instead, I’ll show you the last validation class method, which is quite useful for checking email addresses. So, jump into the next section to find out more about how this is done.

{mospagebreak title=The big challenge: checking email addresses with the “validateEmail()” method}

For anyone who has spent a long time writing validation routines, verifying email addresses is a challenging task. In the good old days, a robust email pattern coded in a regular expression was, most of the time, good enough to make sure that a user had entered a well-formed email address. Now, things are different, considering the vast number of current email domains. However, in order to keep the method’s source code simple and readable, I’ll walk through an intermediate example, and instruct the method to check only for well-formed addresses and existing domains in the DNS. Its signature is as follows:

public function validateEmail($field,$errorMessage){
    if(!isset($_POST[$field])||!preg_match(“
/.+@.+..+./”,$_POST
[$field])||!checkdnsrr(array_pop(explode(“@”,$_POST
[$field])),”MX
“)){
        $this->errors[]=$errorMessage;
    }
}

 

As shown above, the method verifies whether the supplied email address is at least well-formed, without troubling things too much with complex patterns. It then searches in the DNS for the corresponding MX records, in order to determine whether the domain part corresponds to a real email domain. To perform this task, I use the “checkdnsrr()” PHP built-in function, which is extremely helpful when searching DNS records. Of course, this fact doesn’t mean that the user really exists, but it’s a decent way to check for the existence of a given email domain.

From this point onward, you can make your own way either by improving the effectiveness of this method or writing a full-fledged alternative solution, in order to verify user-supplied email addresses.

Now, in case you don’t know, the PHP “checkdnsrr()” function isn’t available on Windows systems, so here’s the alternative “windnsrr()”function, which essentially performs the same task on Microsoft servers:

private function windnsrr($hostName,$recType=”){
    if(!empty($hostName)){
        if($recType==”)$recType=”MX”;
        exec(“nslookup -type=$recType $hostName”,$result);
        foreach($result as $line){
            if(preg_match(“/^$hostName/”,$line)){
                return true;
            }
        }
        return false;
    }
    return false;
}

And eventually, if you’re running your PHP applications on a Windows server, the “validateEmail()” method should be rewritten like this:

public function validateEmail($field,$errorMessage){
    if(!isset($_POST[$field])||!preg_match(“
/.+@.+..+./”,$_POST
[$field])||!$this->windnsrr(array_pop(explode(“@”,$_POST
[$field])),”MX
“)){
        $this->errors[]=$errorMessage;
    }
}

After having defined the last checking method of the class, the only thing left to complete the definition of the form “validator” class consists of including two useful corollaries: the “checkErrors()” and “displayErrors()” methods.

{mospagebreak title=Checking for errors: defining the “checkErrors()” and displayErrors()” methods}

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!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan