HomePHP Page 3 - Building An Extensible Form Validator Class
The Bare Bones - PHP
Wondering what OOP can do for you? Well, wonder no more - thisarticle demonstrates how OOP can save you time and effort by building aPHP-based Form Validator object to validate HTML form input. In additionto a detailed walkthrough of the process of constructing a PHP class totest user input, this article also includes usage examples and a brieflook at some powerful open-source alternatives.
So that's the theory. Let's now spend a few minutes discussing the rationale behind the FormValidator object I plan to build.
Stripped down to its bare bones, my FormValidator class consists of two components:
1. A series of methods that accept the data to be validated as method arguments, test this data to see whether or not it is valid (however "valid" may be defined within the scope of the method), and return an appropriate result code.
2. A PHP structure (here, an associative array) that holds a list of all the errors encountered during the validation process, and a series of methods to manipulate this structure.
As you will see, these two basic components make it possible to build a very simple (and yet very useful) FormValidator object, one that exposes a number of generic methods. It's important to note, however, that these methods will have nothing to do with the visual presentation of either the form or the form's result page; rather, they provide a simple API to perform validation of the data entered into the form, and are designed for use by server-side scripts which are more closely connected to the presentation layer.