验证类

浏览:2025 最后更新:2016-08-15 08:59 分类:示例
<?php
class Validate{
    private $arr = array(
        'rules' => array(       //规则列表
            'qq'      => "/^\d{4,13}$/",
            'sex'     => "/^\d{1}$/",
            'phone'   => "/^[1]{1}[3|4|5|7|8]{1}\d{9}$/",
            'email'   => "/^(?:[a-z1-9]{1})(?:[a-z0-9-_]{1,15})@(?:[a-z0-9-_.]{1,8})\.([a-z0-9-_.]{2,3})$/"
        ),
        'ru_msg' => array(//错误消息
            'qq'        => "QQ有误",
            'sex'       => "性别有误",
            'phone'     => "手机号码错误",
            'email'     => "邮箱格式有误"
        ),
        'required' => array('phone'),//必填项
        'rq_msg'   => array('phone'=>'手机不能为空') //必填项错误信息
    );
    private $rules;
    private $ru_msg;
    private $required;
    private $rq_msg;
    private $rulesField;

    public function __construct($arr=array('rules'=>array(),'ru_msg'=>array(),'required'=>array(),'rq_msg'=>array())){
        foreach($arr as $k=>$v){
            $this->$k = array_merge($arr[$k],$this->arr[$k]);
        }
        $this->rulesField    = array_keys($this->arr['rules']);
    }
    public function check($arr=array()){
        $return=array();
        $return['status'] = 1;
        foreach($arr as $k=>$v){
            if(in_array($k,$this->required) && mb_strlen($v,'utf-8')==0){
                //必填项 - 数组格式
                return array('status'=>0,'field'=>$k,'msg'=>$this->rq_msg[$k]);
                //必填项 - json格式
                //exit(json_encode(array('status'=>0,'field'=>$k,'msg'=>$this->rq_msg[$k])))
            }

            if(in_array($k,$this->rulesField)){
              if(mb_strlen($v,'utf-8')>0){

                $return = self::excu($this->rules[$k],$k,$v);
              }
            }
            if($return['status']==0){
                //错误信息 - 数组格式
                  return $return;
                //错误信息 - json格式
                //exit(json_encode($return));
            }
        }
    }
    private function excu($pattern,$key,$value){
         $return = array();
        $return['status'] = preg_match($pattern, strtolower($value)) ?  1 : 0;
        $return['field'] = $key;
        $return['msg'] = $this->ru_msg[$key];
        return $return;
    }
}
?>
require "Validate.class.php";
$validate = new Validate();//传一个数组
$res = $validate->check($_POST);
评论( 相关
后面还有条评论,点击查看>>