You, as a PHP developer, know that one of the most common and crucial tasks that a PHP application must perform is validating data, generally coming from users or visitors of a web site. In object-based programs, this process is usually delegated to a full-blown validation library, but there are cases where it’s also possible to combine the functionality of a library like this with the capability provided by a simpler helper. In this particular case, I’m going to demonstrate how to build a basic helper class that will validate inputted data, without boasting the complexity of a fully-loaded library. Now that I have clarified that point, please take a look at the initial definition of this validation helper class, which looks like this: class ValidatorHelper { // constructor not implemented public function __construct(){}
// validate integer public function validate_int($value, $min, $max) { return filter_var($value, FILTER_VALIDATE_INT, array('options' => array('min_range' => $min, 'max_range' => $max))); }
// validate float number public function validate_float($value) { return filter_var($value, FILTER_VALIDATE_FLOAT); } } As shown above, the whole new validation helper class is comprised of only a couple of methods, apart from the constructor, for validating integers and float numbers respectively. Also, it’s worthwhile to notice that the pertinent validation tasks are accomplished by using the PHP filter extension. This makes for a truly no-brainer process, but it’s also possible to replace the filters with custom methods that perform the same validation processes. So far, everything looks pretty good. At this stage I've developed a validation helper class that verifies integers and float numbers. While this can be pretty useful as a starting point, it’s possible to aggregate more functionality to the helper class by coding other methods that validate other data types. Based on that premise, in the last section of this tutorial I’m going to add a pair of additional methods to the helper class, which will be charged with validating alphabetic and alphanumeric values. To see how these methods will be defined, go ahead and read the following segment. It’s only one click away.
blog comments powered by Disqus |
|
|
|
|
|
|
|