PHP验证类的封装与使用方法详解


Posted in PHP onJanuary 10, 2019

本文实例讲述了PHP验证类的封装与使用方法。分享给大家供大家参考,具体如下:

<?php
/**
 * Created by PhpStorm.
 * User: jiqing
 * Date: 18-7-24
 * Time: 下午4:36
 * 常用验证
 */
class Valid
{
 static protected $error;
 static protected $error_tips = [
  'tel' => '手机号格式有误',
  'email' => '邮箱格式有误',
  'max_len' => '参数长度不能超过最大长度',
  'min_len' => '参数长度不能小于最小长度',
  'required' => '缺少参数'
 ];
 // required|max_len,100|min_len,6
 public function validate($field, $rules)
 {
  $rules = explode('|', $rules);
  foreach ($rules as $rule) {
   $method = null;
   $param = null;
   // Check if we have rule parameters
   if (strstr($rule, ',') !== false) {
    $rule = explode(',', $rule);
    $method = 'check_'.$rule[0];
    $param = $rule[1];
    $rule = $rule[0];
   } else {
    $method = 'check_'.$rule;
   }
   $method_array = get_class_methods(new Valid());
   if (!in_array($method,$method_array)) {
    self::$error[] = "Method not exist.";
   }
   if (!self::$method($field,$param)) {
    self::$error[] = self::$error_tips[$rule] ? self::$error_tips[$rule] : '参数格式有误';
   }
  }
  if (count(self::$error) == 0) {
   return 0;
  }
  return self::$error[0]; // 返回第一个错误
 }
 public static function check_required($field) {
  if (isset($field) && ($field === false || $field === 0 || $field === 0.0 || $field === '0' || !empty($field))) {
   return true;
  } else {
   return false;
  }
 }
 public static function check_tel($field) {
  if(preg_match("/^1[345678]{1}\d{9}$/",$field)){
   return true;
  }else{
   return false;
  }
 }
 public static function check_email($field) {
  if(preg_match("/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/",$field)){
   return true;
  }else{
   return false;
  }
 }
 public static function check_max_len($field,$param = null) {
  if (function_exists('mb_strlen')) {
   if (mb_strlen($field) <= (int) $param) {
    return true;
   } else {
    return false;
   }
  } else {
   if (strlen($field) <= (int) $param) {
    return true;
   } else {
    return false;
   }
  }
 }
 public static function check_min_len($field,$param = null) {
  if (function_exists('mb_strlen')) {
   if (mb_strlen($field) >= (int) $param) {
    return true;
   } else {
    return false;
   }
  } else {
   if (strlen($field) >= (int) $param) {
    return true;
   } else {
    return false;
   }
  }
 }
 public static function check_regex($field, $param = null)
 {
  $regex = $param;
  if (preg_match($regex, $field)) {
   return true;
  } else {
   return false;
  }
 }
}

基本满足需求。

vendor('Func.Valid');
if ($res = Valid::validate('152','required|regex,/^1[345678]{1}\d{9}$/')) {
 $this->json->setErr(10001,$res);
 $this->json->Send();
}

封装很有意思,这个类唯一的亮点,就是可以复合验证。并且支持正则。而且里面的验证方法还可以单独使用。

vendor('Func.Valid');
if (!Valid::check_tel('152')) {
 $this->json->setErr(10001,'手机号有误');
 $this->json->Send();
}

勇敢的封装,利国利民。

继续封装,支持数组传参。

<?php
/**
 * Created by PhpStorm.
 * User: jiqing
 * Date: 18-7-24
 * Time: 下午4:36
 * 常用验证
 */
class Valid
{
 static protected $error;
 static protected $error_tips = [
  'tel' => '手机号格式有误',
  'email' => '邮箱格式有误',
  'max_len' => '参数长度不能超过最大长度',
  'min_len' => '参数长度不能小于最小长度',
  'required' => '缺少参数'
 ];
 /**
  * @param $validators array array('email' => 'required|valid_email')
  * @param $input array post数据
  * @return string
  */
 public function is_valid($validators, $input) {
  foreach ($validators as $field => $rules) {
   if (!isset($input[$field]) || empty($input[$field])) {
    self::$error[] = "缺少参数";
   }
   $rules = explode('|', $rules);
   foreach ($rules as $rule) {
    $method = null;
    $param = null;
    // Check if we have rule parameters
    if (strstr($rule, ',') !== false) {
     $rule = explode(',', $rule);
     $method = 'check_'.$rule[0];
     $param = $rule[1];
     $rule = $rule[0];
    } else {
     $method = 'check_'.$rule;
    }
    $method_array = get_class_methods(new Valid());
    if (!in_array($method,$method_array)) {
     self::$error[] = "Method not exist.";
    }
    if (!self::$method($input[$field],$param)) {
     self::$error[] = self::$error_tips[$rule] ? self::$error_tips[$rule] : '参数格式有误';
    }
   }
  }
  if (count(self::$error) == 0) {
   return 0;
  }
  return self::$error[0]; // 返回第一个错误
 }
 /**
  * @param $field string 验证字段
  * @param $rules string 验证规则 required|max_len,100|min_len,6
  * @return string
  */
 public function validate($field, $rules)
 {
  $rules = explode('|', $rules);
  foreach ($rules as $rule) {
   $method = null;
   $param = null;
   // Check if we have rule parameters
   if (strstr($rule, ',') !== false) {
    $rule = explode(',', $rule);
    $method = 'check_'.$rule[0];
    $param = $rule[1];
    $rule = $rule[0];
   } else {
    $method = 'check_'.$rule;
   }
   $method_array = get_class_methods(new Valid());
   if (!in_array($method,$method_array)) {
    self::$error[] = "Method not exist.";
   }
   if (!self::$method($field,$param)) {
    self::$error[] = self::$error_tips[$rule] ? self::$error_tips[$rule] : '参数格式有误';
   }
  }
  if (count(self::$error) == 0) {
   return 0;
  }
  return self::$error[0]; // 返回第一个错误
 }
 public static function check_required($field) {
  if (isset($field) && ($field === false || $field === 0 || $field === 0.0 || $field === '0' || !empty($field))) {
   return true;
  } else {
   return false;
  }
 }
 /**
  * 简写
  * @param $field
  * @return bool
  */
 public static function check_r($field) {
  if (isset($field) && ($field === false || $field === 0 || $field === 0.0 || $field === '0' || !empty($field))) {
   return true;
  } else {
   return false;
  }
 }
 public static function check_tel($field) {
  if(preg_match("/^1[345678]{1}\d{9}$/",$field)){
   return true;
  }else{
   return false;
  }
 }
 public static function check_email($field) {
  if(preg_match("/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/",$field)){
   return true;
  }else{
   return false;
  }
 }
 public static function check_max_len($field,$param = null) {
  if (function_exists('mb_strlen')) {
   if (mb_strlen($field) <= (int) $param) {
    return true;
   } else {
    return false;
   }
  } else {
   if (strlen($field) <= (int) $param) {
    return true;
   } else {
    return false;
   }
  }
 }
 public static function check_min_len($field,$param = null) {
  if (function_exists('mb_strlen')) {
   if (mb_strlen($field) >= (int) $param) {
    return true;
   } else {
    return false;
   }
  } else {
   if (strlen($field) >= (int) $param) {
    return true;
   } else {
    return false;
   }
  }
 }
 public static function check_regex($field, $param = null)
 {
  $regex = $param;
  if (preg_match($regex, $field)) {
   return true;
  } else {
   return false;
  }
 }
}

使用如下

vendor('Func.Valid');
$validators = [
 'tel' => 'required|tel',
 'name' => 'required',
 'email' => 'r|email',
 'password' => 'r|min_len,6|max_len,12'
];
if ($err = Valid::is_valid($validators,$_POST)) {
 $this->json->setErr(10001,$err);
 $this->json->Send();
}

PHP验证类的封装与使用方法详解

继续优化!支持错误提示中,添加参数。

<?php
/**
 * Created by PhpStorm.
 * User: jiqing
 * Date: 18-7-24
 * Time: 下午4:36
 * 常用验证
 */
class Valid
{
 static protected $error;
 /**
  * @param $validators array array('email' => 'required|valid_email')
  * @param $input array post数据
  * @return string
  */
 public function is_valid($validators, $input) {
  foreach ($validators as $field => $rules) {
   if (!isset($input[$field]) || empty($input[$field])) {
    self::$error[] = "缺少参数";
   }
   $rules = explode('|', $rules);
   foreach ($rules as $rule) {
    $method = null;
    $param = null;
    // Check if we have rule parameters
    if (strstr($rule, ',') !== false) {
     $rule = explode(',', $rule);
     $method = 'check_'.$rule[0];
     $param = $rule[1];
     $rule = $rule[0];
    } else {
     $method = 'check_'.$rule;
    }
    $method_array = get_class_methods(new Valid());
    if (!in_array($method,$method_array)) {
     self::$error[] = "Method not exist.";
    }
    if (!self::$method($input[$field],$param)) {
     self::$error[] = self::get_error_tips($rule,$param);
    }
   }
  }
  if (count(self::$error) == 0) {
   return 0;
  }
  return self::$error[0]; // 返回第一个错误
 }
 /**
  * @param $field string 验证字段
  * @param $rules string 验证规则 required|max_len,100|min_len,6
  * @return string
  */
 public function validate($field, $rules)
 {
  $rules = explode('|', $rules);
  foreach ($rules as $rule) {
   $method = null;
   $param = null;
   // Check if we have rule parameters
   if (strstr($rule, ',') !== false) {
    $rule = explode(',', $rule);
    $method = 'check_'.$rule[0];
    $param = $rule[1];
    $rule = $rule[0];
   } else {
    $method = 'check_'.$rule;
   }
   $method_array = get_class_methods(new Valid());
   if (!in_array($method,$method_array)) {
    self::$error[] = "Method not exist.";
   }
   if (!self::$method($field,$param)) {
    self::$error[] = self::get_error_tips($rule,$param);
   }
  }
  if (count(self::$error) == 0) {
   return 0;
  }
  return self::$error[0]; // 返回第一个错误
 }
 /**
  * 灵活获取参数
  * @param $rule
  * @param $param
  */
 public static function get_error_tips($rule,$param) {
  $error_tips = [
   'tel' => '手机号格式有误',
   'email' => '邮箱格式有误',
   'max_len' => '参数长度不能超过最大长度'.$param,
   'min_len' => '参数长度不能小于最小长度'.$param,
   'required' => '缺少参数',
   'r' => '缺少参数'
  ];
  return $error_tips[$rule] ? $error_tips[$rule] : '参数格式有误';
 }
 public static function check_required($field) {
  if (isset($field) && ($field === false || $field === 0 || $field === 0.0 || $field === '0' || !empty($field))) {
   return true;
  } else {
   return false;
  }
 }
 /**
  * 简写
  * @param $field
  * @return bool
  */
 public static function check_r($field) {
  if (isset($field) && ($field === false || $field === 0 || $field === 0.0 || $field === '0' || !empty($field))) {
   return true;
  } else {
   return false;
  }
 }
 public static function check_tel($field) {
  if(preg_match("/^1[345678]{1}\d{9}$/",$field)){
   return true;
  }else{
   return false;
  }
 }
 public static function check_email($field) {
  if(preg_match("/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/",$field)){
   return true;
  }else{
   return false;
  }
 }
 public static function check_max_len($field,$param = null) {
  if (function_exists('mb_strlen')) {
   if (mb_strlen($field) <= (int) $param) {
    return true;
   } else {
    return false;
   }
  } else {
   if (strlen($field) <= (int) $param) {
    return true;
   } else {
    return false;
   }
  }
 }
 public static function check_min_len($field,$param = null) {
  if (function_exists('mb_strlen')) {
   if (mb_strlen($field) >= (int) $param) {
    return true;
   } else {
    return false;
   }
  } else {
   if (strlen($field) >= (int) $param) {
    return true;
   } else {
    return false;
   }
  }
 }
 public static function check_regex($field, $param = null)
 {
  $regex = $param;
  if (preg_match($regex, $field)) {
   return true;
  } else {
   return false;
  }
 }
}

PHP验证类的封装与使用方法详解

PHP 相关文章推荐
我的论坛源代码(九)
Oct 09 PHP
PHP 采集心得技巧
May 15 PHP
纯真IP数据库的应用 IP地址转化成十进制
Jun 14 PHP
PHP 字符截取 解决中文的截取问题,不用mb系列
Sep 29 PHP
php快速url重写更新版[需php 5.30以上]
Apr 25 PHP
php中将网址转换为超链接的函数
Sep 02 PHP
PHP file_get_contents设置超时处理方法
Sep 30 PHP
C/S和B/S两种架构区别与优缺点分析
Oct 23 PHP
php使用session二维数组实例
Nov 06 PHP
Zend Framework教程之Zend_Helpers动作助手ViewRenderer用法详解
Jul 20 PHP
thinkphp的dump函数无输出实例代码
Nov 15 PHP
动态表单验证的操作方法和TP框架里面的ajax表单验证
Jul 19 PHP
tp5(thinkPHP5)框架数据库Db增删改查常见操作总结
Jan 10 #PHP
tp5(thinkPHP5)框架实现多数据库查询的方法
Jan 10 #PHP
tp5框架使用composer实现日志记录功能示例
Jan 10 #PHP
PHP微信支付结果通知与回调策略分析
Jan 10 #PHP
php如何利用pecl安装mongodb扩展详解
Jan 09 #PHP
PHP如何通过表单直接提交大文件详解
Jan 08 #PHP
Laravel 队列使用的实现
Jan 08 #PHP
You might like
windwos下使用php连接oracle数据库的过程分享
2014/05/26 PHP
php常用文件操作函数汇总
2014/11/22 PHP
PHP中include()与require()的区别说明
2017/02/14 PHP
弹出模态框modal的实现方法及实例
2017/09/19 PHP
PHP实现数据四舍五入的方法小结【4种方法】
2019/03/27 PHP
宝塔面板在NGINX环境中TP5.1如何运行?
2021/03/09 PHP
javascript 写类方式之六
2009/07/05 Javascript
Jquery中给animation加更多的运作效果实例
2013/09/05 Javascript
javascript实现Email邮件显示与删除功能
2015/11/21 Javascript
JavaScript中的原型prototype完全解析
2016/05/10 Javascript
Javascript中级语法快速入手
2016/07/30 Javascript
Vue.js路由组件vue-router使用方法详解
2016/12/02 Javascript
JS中利用localStorage防止页面动态添加数据刷新后数据丢失
2017/03/10 Javascript
JavaScript中Object基础内部方法图
2018/02/05 Javascript
vue强制刷新组件的方法示例
2019/02/28 Javascript
vue flex 布局实现div均分自动换行的示例代码
2020/08/05 Javascript
[46:43]DOTA2上海特级锦标赛主赛事日 - 1 胜者组第一轮#2LGD VS MVP.Phx第二局
2016/03/02 DOTA
Python获取Windows或Linux主机名称通用函数分享
2014/11/22 Python
python输出指定月份日历的方法
2015/04/23 Python
Python使用装饰器进行django开发实例代码
2018/02/06 Python
django用户注册、登录、注销和用户扩展的示例
2018/03/19 Python
Python Pandas找到缺失值的位置方法
2018/04/12 Python
Django 对象关系映射(ORM)源码详解
2019/08/06 Python
python sorted方法和列表使用解析
2019/11/18 Python
windows下python安装pip方法详解
2020/02/10 Python
Python写出新冠状病毒确诊人数地图的方法
2020/02/12 Python
python UDF 实现对csv批量md5加密操作
2021/01/01 Python
浅谈CSS3 动画卡顿解决方案
2019/01/02 HTML / CSS
app内嵌H5 webview 本地缓存问题的解决
2020/10/19 HTML / CSS
南京软件公司的.net程序员笔试题
2014/08/31 面试题
军校本科大学生自我评价
2014/01/14 职场文书
幼儿园元旦家长感言
2014/02/27 职场文书
教师师德演讲稿
2014/05/06 职场文书
实习指导教师评语
2014/12/30 职场文书
《我在为谁工作》:工作的质量往往决定生活的质量
2019/12/27 职场文书
MySQL事务操作的四大特性以及并发事务问题
2022/04/12 MySQL