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)私有的构造方法 ...
随机推荐
- ReflectionZ_测试_01
1.Java代码 public class TreflectionZ { public static void main(String[] args) throws Exception { Class ...
- Hyper:基于Hypervisor的容器化解决方案
近日,初创公司HyperHQ发布了他们的开源项目Hyper,Hyper是一个可以在hypervisor上运行Docker镜像的引擎,它融合了Docker容器和虚拟机的优点,旨在打造一个性能更好.更安全 ...
- ubuntu 14.04中安装 ruby on rails 环境(填坑版) 呕血推荐
环境:在win7 上Vmware虚拟机环境中安装的ubuntu 14.04 开发相关: ruby 2.2.0 rails 4.2.0 sublime text 3 本文说明:所有的命令均在$ 之后,若 ...
- ImageView显示网络上的图片
ImageView显示网络上的图片 一.简介 二.方法 1)ImageView显示网络上的图片方法 第一步:从网络上下载图片 byte[] byteArr = downImage();//这个是自己写 ...
- Educational Codeforces Round 23F
http://codeforces.com/contest/817/problem/F 无限长的数组,刚开始每一位是0,三种操作,1,把(l,r)之间不是1的变成1,2,把(l,r)之间不是0的变成0 ...
- MySQL学习笔记2018-02-07更新
前言:本人wechat:YWNlODAyMzU5MTEzMTQ=. 如果内容有错,请指出来. win10下安装 https://dev.mysql.com/downloads/mysql/下载并解压m ...
- Windows系统下MySQL解压版添加到系统服务
MySQL软件版本:64位 5.7.12 1.首先配置MySQL的环境变量,在系统环境变量Path的开头添加MySQL的bin目录的路径,以“;”结束,我的路径配置如下: 2.修改MySQL根目录下的 ...
- Android Afinal框架学习(一) FinalDb 数据库操作
框架地址:https://github.com/yangfuhai/afinal 对应源码: net.tsz.afinal.annotation.sqlite.* net.tsz.afinal.db. ...
- Is possible develop iOS game with Delphi Xe4 ? Pascal
下面的计划: 评估用Delphi XE4来开发游戏的可行性. 以及成本. (代价过大的话 估计还是不会被接受 所以某个角度来说这是个玩具) . 有几个选择, Asphyre 4.0 之后作者lifep ...
- c++ 字符串查找函数
头文件:#include <string.h> 定义函数:int strcasecmp (const char *s1, const char *s2); 函数说明:strcasecmp( ...