Snippets     

Form validator class
Description: Form validator class with checks like isNumber, isInteger, isAlpha, etc.
Language: PHP
Category: RegEx

<?php
// PHP 5

// class definition
// class encapsulating data validation functions
class formValidator {

    // define properties
    private $_errorList;

    // define methods
    // constructor
    public function __construct() {
        $this->resetErrorList();
    }

    // initialize error list
    private function resetErrorList() {
        $this->_errorList = array();
    }

    // check whether input is empty
    public function isEmpty($value) {
        return (!isset($value) || trim($value) == '') ? true : false;
    }

    // check whether input is a string
    public function isString($value) {
        return is_string($value);
    }

    // check whether input is a number
    public function isNumber($value) {
        return is_numeric($value);
    }

    // check whether input is an integer
    public function isInteger($value) {
        return (intval($value) == $value) ? true : false;
    }

    // check whether input is alphabetic
    public function isAlpha($value) {
        return preg_match('/^[a-zA-Z]+$/', $value);
    }

    // check whether input is within a numeric range
    public function isWithinRange($value, $min, $max) {
        return (is_numeric($value) && $value >= $min && $value <= $max) ? true : false;
    }
    
    // check whether input is a valid email address
    public function isEmailAddress($value) {
        return eregi('^([a-z0-9])+([\.a-z0-9_-])*@([a-z0-9_-])+(\.[a-z0-9_-]+)*\.([a-z]{2,6})$', $value);
    }

    // check if a value exists in an array
    public function isInArray($array, $value) {
        return in_array($value, $array);
    }

    // add an error to the error list
    public function addError($field, $message) {
        $this->_errorList[] = array('field' => $field, 'message' => $message);
    }

    // check if errors exist in the error list
    public function isError() {
        return (sizeof($this->_errorList) > 0) ? true : false;
    }

    // return the error list to the caller
    public function getErrorList() {
        return $this->_errorList;
    }

    // destructor
    // de-initialize error list
    public function __destruct() {
        unset($this->_errorList);
    }

// end class definition
}

?> 
Back


  Copyright 2009 Isaac Roach iroach@gmail.com