一款健壮体验佳的应用,无论在客户端及服务端都应当对用户所提交的数据(表单)进行验证。ThinkPHP 的验证器(表单验证)类 Validate 可以方便地为开发者们提供服务端的验证功能。
本文测试环境:
服务端系统:CentOS release 6.10 (Final)
服务器软件:Nginx 1.14.1
服务端语言:PHP 5.6.36
PHP 框架:ThinkPHP 5.1.38 LTS
一、ThinkPHP 5.1 验证器(表单验证) 类 Validate 的常规用法
示例:定义一个 \app\admin\validate\User 验证器类用于 User 的验证。
1. 在 admin 模块下的 validate 文件夹下新建一个 User.php 。V 5.1.15+,可以使用下面的指令快速生成。
php think make:validate admin/User
2. 定义验证规则
<?php
namespace app\admin\validate;
use think\Validate;
class User extends Validate{
// 验证规则
protected $rule = [
'name' => 'require|max:25|checkName:用户名不能为 admin',
'age' => 'number|between:1,120',
'email' => 'email'
];
// 验证错误提示信息
protected $message = [
'name.require' => '用户名必须传递',
'name.max' => '用户名不能超过25个字符',
'age.number' => '年龄必须是数字',
'age.between' => '年龄只能在1-120之间',
'email' => '邮箱格式错误'
];
// 验证场景
protected $scene = [
'register' => ['name','age','email'],
'change' => ['age','email']
];
// 自定义验证规则。5个参数依次为:验证数据,验证规则,全部数据(数组),字段名,字段描述(后面三个根据情况选用)。
protected function checkName($value,$rule,$data=[],$name,$desc){
if($value == 'admin'){
return $rule;
}else{
return true;
}
}
}
3. 使用验证器
<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
use app\admin\validate\User;
class User extends Controller{
/**
* 注册
*/
public function save(Request $request){
if(!$request->isPost()){
$this->error('请求失败!');
}
$data = $request->post();
// 1. 实例化验证器类
$validate = new User();
// 2. 选择场景进行验证
if(!$validate->scene('register')->check($data)){
// 3. 获取验证错误信息
$this->error($validate->getError());
}
…
}
/**
* 更新
*/
public function update(Request $request){
if(!$request->isPost()){
$this->error('请求失败!');
}
$data = $request->post();
$validate = new User();
// 默认情况下,一旦有某个数据的验证规则不符合,就会停止后续数据及规则的验证,如果希望批量进行验证可添加方法 batch() 。
$res = $validate->scene('change')->batch()->check($data);
if($res !== true){
// 批量验证如果未通过,返回的是一个错误信息的数组。
dump($validate->getError());
}
…
}
}
二、ThinkPHP 5.1 验证器(表单验证)类 Validate 的内置验证规则
TP 的官方手册上并没有列出所有的内置验证规则,但是我们可以通过阅读其封装类 Validate 来了解它们。
www(WEB 部署目录)/thinkphp/library/think/Validate.php
<?php
…
/**
* 默认规则提示
* @var array
*/
protected static $typeMsg = [
'require' => ':attribute require',
'must' => ':attribute must',
'number' => ':attribute must be numeric',
'integer' => ':attribute must be integer',
'float' => ':attribute must be float',
'boolean' => ':attribute must be bool',
'email' => ':attribute not a valid email address',
'mobile' => ':attribute not a valid mobile',
'array' => ':attribute must be a array',
'accepted' => ':attribute must be yes,on or 1',
'date' => ':attribute not a valid datetime',
'file' => ':attribute not a valid file',
'image' => ':attribute not a valid image',
'alpha' => ':attribute must be alpha',
'alphaNum' => ':attribute must be alpha-numeric',
'alphaDash' => ':attribute must be alpha-numeric, dash, underscore',
'activeUrl' => ':attribute not a valid domain or ip',
'chs' => ':attribute must be chinese',
'chsAlpha' => ':attribute must be chinese or alpha',
'chsAlphaNum' => ':attribute must be chinese,alpha-numeric',
'chsDash' => ':attribute must be chinese,alpha-numeric,underscore, dash',
'url' => ':attribute not a valid url',
'ip' => ':attribute not a valid ip',
'dateFormat' => ':attribute must be dateFormat of :rule',
'in' => ':attribute must be in :rule',
'notIn' => ':attribute be notin :rule',
'between' => ':attribute must between :1 - :2',
'notBetween' => ':attribute not between :1 - :2',
'length' => 'size of :attribute must be :rule',
'max' => 'max size of :attribute must be :rule',
'min' => 'min size of :attribute must be :rule',
'after' => ':attribute cannot be less than :rule',
'before' => ':attribute cannot exceed :rule',
'afterWith' => ':attribute cannot be less than :rule',
'beforeWith' => ':attribute cannot exceed :rule',
'expire' => ':attribute not within :rule',
'allowIp' => 'access IP is not allowed',
'denyIp' => 'access IP denied',
'confirm' => ':attribute out of accord with :2',
'different' => ':attribute cannot be same with :2',
'egt' => ':attribute must greater than or equal :rule',
'gt' => ':attribute must greater than :rule',
'elt' => ':attribute must less than or equal :rule',
'lt' => ':attribute must less than :rule',
'eq' => ':attribute must equal :rule',
'unique' => ':attribute has exists',
'regex' => ':attribute not conform to the rules',
'method' => 'invalid Request method',
'token' => 'invalid token',
'fileSize' => 'filesize not match',
'fileExt' => 'extensions to upload is not allowed',
'fileMime' => 'mimetype to upload is not allowed',
];
…
三、ThinkPHP 5.1 验证器(表单验证)类 Validate 的一些坑
在 TP 5.1 中聚合方法无效,错误信息必须使用 message 属性定义。
错误:
<?php
namespace app\admin\validate;
use think\Validate;
class User extends Validate{
// 将验证错误聚合到一个数组中的方法在 TP 5.1 中无效。
protected $rule = [
['name','require|max:25','用户名必须传递|用户名不能超过25个字符']
];
protected $scene = [
'register' => ['name']
];
}
● 更多关于 ThinkPHP 5.1 验证器(表单验证)类 Validate 的资料可查阅:验证器 – ThinkPHP 5.1 完全开发手册