HomePHP Page 3 - Building a PHP 5 Form Processor: Coding the Form Generator Module
Integrating client-side validation: defining the signature of the “JSGenerator” class - PHP
Most developers must deal with the job of developing robust data validation for forms on a regular basis. Nobody wants to write the same code over and over, so this article (the first of three in a series) will help you develop an extensible and reusable form validation package. By the end of the article, you will have all the relevant classes that integrate the generator module of the PHP form processor.
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:
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.