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
/**
* 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封装验证类的更多相关文章
- 封装application类
<?php //判断用户是否是通过入口文件访问 if(!defined('ACCESS')){ echo '非法请求'; die; } //封装初始化类 cla ...
- C# System.Attribute(验证类)
本文以一个项目中通用的验证类来举例说明如何使用自定义Attribute来扩展元数据. 在项目中,我们为了保证各个层次之间的松藕合,通常把在各个层次之间传递数据的封装在一个称为实体类的类中,比如Act ...
- 适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
适用于app.config与web.config的ConfigUtil读写工具类 之前文章:<两种读写配置文件的方案(app.config与web.config通用)>,现在重新整理一 ...
- SpringMVC 自动封装枚举类的方法
springmvc默认无法自动封装枚举类,解决方法如下: 1.枚举类 public enum GoodsPromoteEnum { /** * 0 精品 */ fine("精品", ...
- JavaScript 数据验证类
JavaScript 数据验证类 /* JavaScript:验证类 author:杨波 date:20160323 1.用户名验证 2.密码验证 3.重复密码验证 4.邮箱验证 5.手机号验证 6. ...
- C# 通用验证类 支持 WPF,MVC,Winform
验证方式, 通过继承 IDataErrorInfo接口 和 DataAnnotations 解释标记语言而实现, 为了能在WPF上通用,所了也要继承属性更改通知接口INotifyPropertyC ...
- C# - DataValid数据验证类
从EasyCode 摘取下来的数据验证类 using System; using System.Collections.Generic; using System.Text; namespace Le ...
- iOS NSURLSession 封装下载类
周六日鼓捣NSURLSession,效率虽然低下,最后还是有了一点点眉目.昨天和汤老师一起测试,又对它加深了一点理解.趁热打铁,先总结一下. 封装的类,对外用的方法,我写的是类方法,所以,在类方法中, ...
- 封装mysql类
类: <?phpheader("content-type:text/html;charset=utf-8");//封装一个类/*掌握满足单例模式的必要条件(1)私有的构造方法 ...
随机推荐
- 分享:自定义JAVA注解
元注解 元注解指用来定义注解的注解,例如:@Retention @Target Inherited @Documented等等.最为重要和经常使用的是@Retention @Target. @Rete ...
- npm install 时总是报phantomjs-prebuilt@2.1.14安装失败
在npm install时总是报如下错误, 尝试单独安装:npm install phantomjs-prebuilt@2.1.14 还是报错 Please report this full log ...
- Mac OS X下实现结束占用某特定端口的进程
---恢复内容开始--- 1.打开终端,使用如下命令: lsof -i:**** 以上命令中,****代表端口号,我们首先要知道哪个(或哪些)进程占用该端口,比如你可以运行 lsof -i:8000, ...
- 第三方库PIL简单使用
PIL为第三方库,需要简单安装,最容易的安装方法 pip install PIL 详细内容见http://effbot.org/imagingbook/ 下面展示一个简单用例:(字母验证码简单实现) ...
- Django进阶Model篇007 - 聚集查询和分组查询
接着前面的例子,举例聚集查询和分组查询例子如下: 1.查询人民邮电出版社出了多少本书 >>> Book.objects.filter(publisher__name='人民邮电出版社 ...
- IOS-社会化分享
一.如何实现社交分享 在iOS中,实现“社交分享”的方法 1.自己编写各个平台的分享代码(代码量较多) 2.利用iOS自带的Social.framework 3.利用第三方的分享框架 友盟分享 ...
- CMD下修改mysql的root用户密码
文章转载自... CMD下,切换到mysql的bin目录下(目录加入到环境变量中绕过此步) 输入 mysql -u root -p,输入旧密码,进入mysql状态 MySQL>use MySQL ...
- windows server 2016 docker 之创建使用虚拟交换机
windows server 2016 Create a virtual switch for Hyper-V virtual machines 操作步骤: 服务器只有一块网卡连接了网络 尝试1: h ...
- Qt 出现“undefined reference to `vtable for”原因总结
http://blog.csdn.net/chenlong12580/article/details/7431104
- Android代码混淆及项目发布方法记录
Android代码混淆及项目发布步骤记录 本来整理了一份Android项目混淆与发布的文档,突然想到何不写篇博客,分享一下呢,如是便有了本文. Android代码混淆及项目发布步骤记录 一.清理 ...