php实现的表单验证类完整示例


Posted in PHP onAugust 13, 2019

本文实例讲述了php实现的表单验证类。分享给大家供大家参考,具体如下:

<?php
/**
 * 用法
 * use Validate\Validator;
 * 
 * $rules = [ 
 *    ['name|名字', 'require|email|in:7,8,9|max:10|min:6|between:6,8|length:2', '名字不能为空|名字必须必须为正确的邮件地址'],
 *    ['test|测试', 'require'],
 *  ];
 * $data = ['name' => '8gAg:'];
 * $validator = new Validator($rules);
 * $validator->addRule(['name|名字', 'regex', '/^[0-8|a-z]+$/', '正则验证失败哦']); //可以为二维数组,有|的正则验证只能通过addRule。
 * $validator->validate($data);
 * $validator->getAllErrors(); //获取所有验证错误 array
 * $validator->getError(); //获取第一条验证错误 string
 * Validator::in('7,8,9', 8); //静态调用
 * Validator::isEmail('375373223@qq.com');
 */
namespace Validate;
class Validator {
  //错误信息
  private $error = [];
  //传入的验证规则
  private $validate = [];
  //需要验证的参数
  private $data = [];
  //添加的规则
  private $add_rules = [];
  //默认错误提示
  private $error_msg = [
    'require' => ':attribute不能为空',
    'number' => ':attribute必须为数字',
    'array'  => ':attribute必须为数组',
    'float'  => ':attribute必须为浮点数',
    'boolean' => ':attribute必须为布尔值',
    'email'  => ':attribute必须为正确的邮件地址',
    'url'   => ':attribute必须为正确的url格式',
    'ip'   => ':attribute必须为正确的ip地址',
    'timestamp' => ':attribute必须为正确的时间戳格式',
    'date'  => ':attribute必须为正确的日期格式',
    'regex'  => ':attribute格式不正确',
    'in'   => ':attribute必须在:range内',
    'notIn'  => ':attribute必须不在:range内',
    'between' => ':attribute必须在:1-:2范围内',
    'notBetween' => ':attribute必须不在:1-:2范围内',
    'max'   => ':attribute最大值为:1',
    'min'   => ':attribute最小值为:1',
    'length' => ':attribute长度必须为:1',
    'confirm' => ':attribute和:1不一致',
    'gt'   => ':attribute必须大于:1',
    'lt'   => ':attribute必须小于:1',
    'egt'   => ':attribute必须大于等于:1',
    'elt'   => ':attribute必须小于等于:1',
    'eq'   => ':attribute必须等于:1',
  ];
  public function __construct($validate = null) {
    $this->validate = $validate;
 }
  /**
   * [validate 验证]
   * @param [type] $data [需要验证的参数]
   * @return [type]    [boolean]
   */
 public function validate($data) {
 $this->data = $data;
    foreach ($this->validate as $key => $item) {
     $item_len = count($item);
     $name = $item[0];
     $rules = $item[1];
     $rules = explode('|', $rules);
     $message = $item_len > 2 ? explode('|', $item[2]) : null;
      $this->check($name, $rules, $message); 
    }
    if(!empty($this->add_rules)) {
     $this->checkAddRules();
    }
    return empty($this->error) ? TRUE : FALSE;
 }
  /**
   * [check 单个字段验证]
   * @param [type] $name  [description]
   * @param [type] $rules  [description]
   * @param [type] $message [description]
   * @return [type]     [null]
   */
 private function check($name, $rules, $message) {
 //$title = $name;
 $rule_name = $title = $name;
 if(strpos($name, '|')) {
  $rule_name = explode('|', $name)[0];
  $title = explode('|', $name)[1];
 }
    foreach ($rules as $i => $rule) {
   $validate_data = isset($this->data[$rule_name]) ? $this->data[$rule_name] : null;
     
     $result = $this->checkResult($rule, $validate_data);
     if(!$result) {
     $error_info = isset($message[$i]) ? $message[$i] : $this->getMessage($title, $rule);
        if($error_info) {
         array_push($this->error, $error_info);
        }
     }
    }
 }
  /**
   * [getMessage 获取验证失败的信息]
   * @param [type] $name [字段名]
   * @param [type] $rule [验证规则]
   * @return [type]    [string OR fail false]
   */
 private function getMessage($name, $rule) {
 $value1 = '';
 $value2 = '';
 $range = '';
 $error_key = $rule;
    if(strpos($rule, ':')) {
     $exp_arr = explode(':', $rule);
     $error_key = $exp_arr[0];
     $range = $exp_arr[1];
     $message_value = explode(',', $exp_arr[1]);
     $value1 = isset($message_value[0]) ? $message_value[0] : '';
     $value2 = isset($message_value[1]) ? $message_value[1] : '';
    }
    if(isset($this->error_msg[$error_key])) {
     return str_replace([':attribute', ':range', ':1', ':2'], [$name, $range, $value1, $value2], $this->error_msg[$error_key]);
    }
 return false;
 }
  /**
   * [checkResult 字段验证]
   * @param [type] $rule     [验证规则]
   * @param [type] $validate_data [需要验证的数据]
   * @return [type]        [boolean]
   */
 private function checkResult($rule, $validate_data) {
    switch ($rule) {
     case 'require':
       return $validate_data != '';
     break;
     case 'number':
       return filter_var($validate_data, FILTER_SANITIZE_NUMBER_INT);
     break;
     case 'array':
       return is_array($validate_data);
     break;
     case 'float':
       return filter_var($validate_data, FILTER_VALIDATE_FLOAT);
     break;
     case 'boolean':
       return filter_var($validate_data, FILTER_VALIDATE_BOOLEAN);
     break;
     case 'email':
       return filter_var($validate_data, FILTER_VALIDATE_EMAIL);
     break;
     case 'url':
       return filter_var($validate_data, FILTER_SANITIZE_URL);
     case 'ip':
       return filter_var($validate_data, FILTER_VALIDATE_IP);
     break;
     case 'timestamp':
       return strtotime(date('Y-m-d H:i:s',$validate_data)) == $validate_data;
     break;
     case 'date': //2017-11-17 12:12:12
       return strtotime($validate_data);
     break;
     default:
         if(strpos($rule, ':')) {
         $rule_arr = explode(':', $rule);
         $func_name = substr($rule, strpos($rule, ':')+1);
         return call_user_func_array([$this, $rule_arr[0]], [$func_name, $validate_data]); 
       }else{
        return call_user_func_array([$this, $rule], [$rule, $validate_data]); 
       }
     break;
    }
 }
  /**
   * [regex 正则验证]
   * @param [type] $rule [description]
   * @param [type] $data [description]
   * @return [type]    [description]
   */
 public static function regex($rule, $data) {
    return filter_var($data, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => $rule]]);
 }
  /**
   * [addRule 添加规则格式 []]
   * @param [type] $rule [description]
   */
 public function addRule($rule) {
 if(is_array(current($rule))) {
  $this->add_rules = array_merge($this->add_rules, $rule);
 }else{
  array_push($this->add_rules, $rule);
 }
 }
  /**
   * [checkAddRules 添加新的规则的验证]
   * @return [type] [description]
   */
 public function checkAddRules() {
 foreach ($this->add_rules as $key => $item) {
  $name = $item[0];
     $message = isset($item[3]) ? $item[3] : null;
     $rule_name = $title = $name;
  if(strpos($name, '|')) {
  $rule_name = explode('|', $name)[0];
  $title = explode('|', $name)[1];
  }
  $validate_data = isset($this->data[$rule_name]) ? $this->data[$rule_name] : null;
     
      $result = $this->checkResult($item[1].':'.$item[2], $validate_data);
     if(!$result) {
     $error_info = isset($message) ? $message : $this->getMessage($title, $item[1]);
       if($error_info) {
         array_push($this->error, $error_info);
       }
     } 
 }
 }
 /**
 * [in description]
 * @param [type] $rule [验证规则]
 * @param [type] $data [需要验证的数据]
 * @return [type]    [boolean]
 */
 public static function in($rule, $data) {
 if(!is_array($rule)) {
  $rule = explode(',', $rule);
 }
    return in_array($data, $rule);
 }
  /**
 * [in description]
 * @param [type] $rule [验证规则]
 * @param [type] $data [需要验证的数据]
 * @return [type]    [boolean]
 */
 public static function notIn($rule, $data) {
    return !$this->in($data, $rule);
 }
  /**
 * [in description]
 * @param [type] $rule [验证规则]
 * @param [type] $data [需要验证的数据]
 * @return [type]    [boolean]
 */
 public static function between($rule, $data) {
 $rule = explode(',', $rule);
    return $data >= $rule[0] && $data <= $rule[1];
 }
  /**
 * [in description]
 * @param [type] $rule [验证规则]
 * @param [type] $data [需要验证的数据]
 * @return [type]    [boolean]
 */
 public static function notBetween($rule, $data) {
 return !$this->between($rule, $data);
 }
  /**
 * [in description]
 * @param [type] $rule [验证规则]
 * @param [type] $data [需要验证的数据]
 * @return [type]    [boolean]
 */
 public static function max($rule, $data) {
 return $data <= $rule;
 }
  /**
 * [in description]
 * @param [type] $rule [验证规则]
 * @param [type] $data [需要验证的数据]
 * @return [type]    [boolean]
 */
 public static function min($rule, $data) {
 return $data >= $rule;
 }
  /**
 * [in description]
 * @param [type] $rule [验证规则]
 * @param [type] $data [需要验证的数据]
 * @return [type]    [boolean]
 */
 public static function length($rule, $data) {
 $length = is_array($data) ? count($data) : strlen($data);
 return $length == $rule;
 }
  /**
 * [in description]
 * @param [type] $rule [验证规则]
 * @param [type] $data [需要验证的数据]
 * @return [type]    [boolean]
 */
 public static function confirm($rule, $data) {
 return isset($this->data[$rule]) && $data == $this->data[$rule];
 }
 public static function gt($rule, $data) {
 return $data > $rule;
 }
  public static function lt($rule, $data) {
 return $data < $rule;
 }
 public static function egt($rule, $data) {
 return $data >= $rule;
 }
  public static function elt($rule, $data) {
 return $data <= $rule;
 }
 public static function eq($rule, $data) {
 return $data == $rule;
 }
  /**
 * [in 获取验证失败的第一条信息]
 * @return [type] [string]
 */
 public function getError() {
    return count($this->error) > 0 ? $this->error[0] : null;
 }
  /**
   * [getAllErrors 获取所有验证失败的信息]
   * @return [type] [array]
   */
 public function getAllErrors() {
    return $this->error;
 }
  /**
   * [__call 调用自定义函数或者]
   * @param [type] $func [验证规则,函数名]
   * @param [type] $data [验证数据]
   * @return [type]    [boollean]
   */
 function __call($func, $data) {
 $func_arr = get_defined_functions();
 if(in_array($func,$func_arr['user'])) {
  return call_user_func($func, $data);
 }else{
  array_push($this->error, '没有' . $func . '这个方法');
 }
  }
  /**
   * [__callStatic 静态方法调用自定义函数或者]
   * @param [type] $func [验证规则,函数名]
   * @param [type] $data [验证数据]
   * @return [type]    [boollean]
   */
  public static function __callStatic($func, $data) {
  if(substr($func, 0, 2) == 'is') {
  return call_user_func_array([new self, 'checkResult'], [strtolower(substr($func, 2)), $data[0]]);
 } 
  }
}
PHP 相关文章推荐
同一空间绑定多个域名而实现访问不同页面的PHP代码
Dec 06 PHP
PHP 编程安全性小结
Jan 08 PHP
paypal即时到账php实现代码
Nov 28 PHP
php短域名转换为实际域名函数
Jan 17 PHP
php expects parameter 1 to be resource, array given 错误
Mar 23 PHP
浅析PHP绘图技术
Jul 03 PHP
php获取mysql字段名称和其它信息的例子
Apr 14 PHP
从零开始学YII2框架(三)扩展插件yii2-gird
Aug 20 PHP
php简单实现MVC
Feb 05 PHP
PHP中strpos、strstr和stripos、stristr函数分析
Jun 11 PHP
PHP的自定义模板引擎
Mar 24 PHP
PHP实现函数内修改外部变量值的方法示例
Dec 28 PHP
thinkphp3.2同时连接两个数据库的简单方法
Aug 13 #PHP
php实现简单的守护进程创建、开启与关闭操作
Aug 13 #PHP
Laravel如何同时连接多个数据库详解
Aug 13 #PHP
Laravel 默认邮箱登录改成用户名登录的实现方法
Aug 12 #PHP
php链式操作的实现方式分析
Aug 12 #PHP
基于PHP实现微信小程序客服消息功能
Aug 12 #PHP
php swoole多进程/多线程用法示例【基于php7nts版】
Aug 12 #PHP
You might like
php 验证码制作(网树注释思想)
2009/07/20 PHP
PHP常用代码大全(新手入门必备)
2010/06/29 PHP
php中instanceof 与 is_a()区别分析
2015/03/03 PHP
Laravel中七个非常有用但很少人知道的Carbon方法
2017/09/21 PHP
PHP反射原理与用法深入分析
2019/09/28 PHP
浅谈Javascript事件处理程序的几种方式
2012/06/27 Javascript
javascript之典型高阶函数应用介绍二
2013/01/10 Javascript
用javascript为页面添加天气显示实现思路及代码
2013/12/02 Javascript
jQuery实现的放大镜效果示例
2016/09/13 Javascript
自制微信公众号一键排版工具
2016/09/22 Javascript
基于KO+BootStrap+MVC实现的分页控件代码分享
2016/11/07 Javascript
简单好用的nodejs 爬虫框架分享
2017/03/26 NodeJs
vue轮播图插件vue-awesome-swiper的使用代码实例
2017/07/10 Javascript
小程序scroll-view安卓机隐藏横向滚动条的实现详解
2019/05/16 Javascript
JS去除字符串最后的逗号实例分析【四种方法】
2019/06/20 Javascript
turn.js异步加载实现翻书效果
2019/07/25 Javascript
Layui实现数据表格中鼠标悬浮图片放大效果,离开时恢复原图的方法
2019/09/11 Javascript
Python实现基于HTTP文件传输实例
2014/11/08 Python
Python二叉搜索树与双向链表转换实现方法
2016/04/29 Python
对python的unittest架构公共参数token提取方法详解
2018/12/17 Python
python Django编写接口并用Jmeter测试的方法
2019/07/31 Python
selenium 多窗口切换的实现(windows)
2020/01/18 Python
python 遗传算法求函数极值的实现代码
2020/02/11 Python
matplotlib 多个图像共用一个colorbar的实现示例
2020/09/10 Python
python 日志模块logging的使用场景及示例
2021/01/04 Python
HTML5 history新特性pushState、replaceState及两者的区别
2015/12/26 HTML / CSS
美国最古老的精致书写工具制造商:A.T. Cross(高仕)
2018/01/30 全球购物
英国Boots旗下太阳镜网站:Boots Designer Sunglasses
2018/07/07 全球购物
英国领先品牌手动工具和电动工具供应商:Tooled Up
2018/11/24 全球购物
英国鲜花递送:Blossoming Gifts
2020/07/10 全球购物
政府法律服务方案
2014/06/14 职场文书
2014大四本科生自我鉴定总结
2014/10/04 职场文书
旷课检讨书范文
2014/10/30 职场文书
党的群众路线调研报告
2014/11/03 职场文书
幼儿园托班开学寄语(2016春季)
2015/12/03 职场文书
Mybatis-Plus 使用 @TableField 自动填充日期
2022/04/26 Java/Android