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)私有的构造方法 ...
随机推荐
- Treflection06_调用静态方法
1. package reflectionZ; import java.lang.reflect.Method; public class Treflection06 { public static ...
- React菜鸟食谱
JSX 用小括号包裹代码防止分号自动插入的bug,用大括号包裹里面的表达式 切记你使用了大括号包裹的 JavaScript 表达式时就不要再到外面套引号了.JSX 会将引号当中的内容识别为字符串而不是 ...
- 使用Mybatis整合spring时报错Injection of autowired dependencies failed;
这是无法自动注入,通过查找,我出错的原因在于配置文件的路径没有写对,在applicationContext.xml中是这样写的. <bean id="sqlSessionFactory ...
- ps(笔记)
窗口 工作区 默认窗口(恢复) ctrl + n 点阵图(像素图) 小方格组成的 alt 键 配合 放大缩小 ppi dpi 打印输出. 画布新建 z键 局部放大 右击实际像素操作 f键 全屏 空格键 ...
- JavaScript中url 传递参数(特殊字符)解决方法及转码解码的介绍
有些符号在URL中是不能直接传递的,如果要在URL中传递这些特殊符号,那么就要使用他们的编码了.下表中列出了一些URL特殊符号及编码 十六进制值 1. + URL 中+号表示空格 %2B 2. 空 ...
- 2017.11.2 Talk to customers for an hour
yesterday::: Hi Huang, For the better performance of the test the Con 6 should be connected all the ...
- Flask中的ORM使用
前言 ORM拓展 安装 数据库设置 使用 关系 单表操作 建表 应用表结构 CRUD 添加查找操作 更新操作 删除操作 一对多 多对多 总结 前言 最近几天接触了一下Flask,在惊叹于其简洁性的同时 ...
- 高性能高并发服务器架构设计探究——以flamigo服务器代码为例
这篇文章我们将介绍服务器的开发,并从多个方面探究如何开发一款高性能高并发的服务器程序. 所谓高性能就是服务器能流畅地处理各个客户端的连接并尽量低延迟地应答客户端的请求:所谓高并发,指的是服务器可以同时 ...
- Happening in delphi world
Happy New Year! Delphi XE5 Update 2 Recent VCL enhancements New product features for old product use ...
- 简单实用的跨域表单POST提交
我们这里使用了iframe嵌套form表单POST提交,很简单,却能满足get|post等任何复杂情况的要求:缺点是没有返回值. 针对需要的地方加上一个iframe嵌套并塞入隐藏form表单,然后获取 ...