Инструменты пользователя

Инструменты сайта


php_validator

Назад

/* public mentod addRules - добавить поля для валидации */
/* public mentod addErrors - добавить ошибку */
/* public method ErrorFields - получить список всех полей, которые имеют ошибку*/
/* public method CountError - получить количество ошибок */
/* public method getErrors - Вывести описание ошибки по полю*/
 
class Validator
{
    var $_errmessages;
    var $_rules;
    var $_errors;
    var $_messages;
    var $_defauleErrorMessage;
    var $_data;
    var $_curElement;
 
    function Reset()
    {
        $this->_errmessages     = array();
        $this->_rules           = array();
        $this->_messages        = array();
        $this->_defauleErrorMessage = array();
    }
 
    function Validator($rules="",$messages="")
    {
        $this->Reset();
        if(is_array($rules))    $this->_rules = $rules;
        if(is_array($messages)) $this->_errmessages = $messages;
 
    }
 
    function addRules($rules,$reset=false)
    {
        if($reset)
            $this->Reset();
        $this->_rules = array_merge($this->_rules,$rules);
    }
 
    function addErrors($errors,$reset=false)
    {
        if($reset)
            $this->Reset();
        $this->_errmessages = array_merge($this->_errmessages,$errors);
    }
 
    function isValid($data)
    {
        $valid = true;
        $this->_data = $data;
 
        foreach($data as $element => $value)
        {
            if(isset($this->_rules[$element]))
            {
                if(!$this->validate($element,$value))
                    $valid = false;
            }
        }
        return $valid;
    }
 
    function validate($element,$value)
    {
        $this->_curElement = $element;
        $rules = $this->_rules[$element];
 
        if(isset($this->_errmessages[$element]))
            $errormessage = $this->_errmessages[$element];
 
        if(is_array($rules))
        {
 
            $valid = true;
            $curErr = array();
            foreach($rules as $rule=>$con)
            {
 
                if(!$this->check($rule,$value,$con))
                {
                    $valid = false;
                    if(isset($errormessage[$rule]))
                        $curErr[]=$errormessage[$rule];
                    else $curErr[]=$this->DefaultErrorMsg($rule);
                }
            }
 
            if(!$valid && !isset($this->_messages[$element]))
                $this->_messages[$element] = $curErr;
            return $valid;
        }
        else
        {
            if(!$this->check($rules,$value))
            {
                if(isset($errormessage))
                    $this->_messages[$element] = $errormessage;    
                else $this->_messages[$element] = $this->DefaultErrorMsg($rules);
                return false;
            }
            else return true;
 
        }
    }
 
    function isint($number)
    {
        $text = (string)$number;
        $textlen = strlen($text);
        if ($textlen==0) return 0;
        for ($i=0;$i < $textlen;$i++)
        { 
            $ch = ord($text{$i});
            if (($ch<48) || ($ch>57)) 
                return 0;
        }
        return true;
    }
 
    function check($rule,$value,$condition=true)
    {
        switch(strtolower($rule))
        {
            case "require":
            {
                return !(trim($value)=="");
            }
            case "maxlength":
            {
                return (strlen($value)<=$condition);
            }       
            case "minlength":
            {
                return (strlen($value)>=$condition);
            }
            case "eqlength":
            {
                return (strlen($value)==$condition);
            }        
            case "equal":
            {
                return ($value==$condition);
            }
            case "numeric":
            {
                return is_numeric($value);
            }   
            case "int":
            {
                return $this->isint($value);
            }   
            case "on":
            {
                return $condition($value);
            }
            case "float":
            {
                $v = (float) $value; 
                return ((string)$v===(string)$value);
            }
            case "min":
            {
                if($value<$condition) return false;
            }
            case "max":
            {
                if($value>$condition) return false;
            } 
            case "gt":
            {
                if($value<$condition) return false;
            }
            case "lt":
            {
                if($value>$condition) return false;
            }
            case "email":
            {
                return preg_match("/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9]+$/",$value,$m);
            }   
        }       
        return true;
    }
 
    function DefaultErrorMsg($rule)
    {
        switch(strtolower($rule))
        {
            case "require"      :    return "Require";        //    
            case "maxlength"    :    return "Over Length"; //        
            case "minlength"    :    return "Under Length";    //    
            case "eqlength"     :    return "Length Mismatch";//        
            case "equal"        :    return "Data Mismatch";//
            case "numeric"      :    return "Numeric Value Require";//
            case "int"          :    return "Integer Value require";
            case "float"        :    return "Float Value require";
            case "gt"           :
            case "min"          :    return "Too small";
            case "lt"           :
            case "max"          :    return "Too high";
            case "date"         :    return "Invalid Date";
            case "email"        :    return "Invalid Email address";
            default             :    return "error";
        }        
        return true;
    }
    function CountError()
    {
        return count($this->_messages);
    }
    function ErrorFields()
    {
        return array_keys($this->_messages);
    }
    function getErrors($element)
    {
        return $this->_messages[$element];
    }
}