## 創建驗證器
~~~
$php think make:validate test@User
~~~
一個完整的驗證器代碼包含`$rule`、`$message`、`$scene`,如下:
~~~
<?php
namespace app\admin\validate;
use think\Validate;
class User extends Validate{
// 校驗規則
protected $rule = [
'name'=>'require',
'__token__'=>'require|token'
];
// 校驗規則
protected $message = [
'code.require'=>'請輸入代碼',
'__token__.require'=>'驗證碼必須輸入',
'__token__.token'=>'請不要重復提交'
];
// 場景設置
protected $scene = [
'add' => ['code','__token__'],
'edit' => ['code','__token__']
];
}
~~~
在控制器中驗證如下。
~~~
<?php
declare (strict_types = 1);
namespace app\test\controller;
use think\Request;
use app\test\validate\UsersValidate;
use think\exception\ValidateException;
// use think\facade\Validate;
class User
{
public function index()
{
$data = ['name' => 'admin',
'email' => 'thinkphp@qq.com',];
try {
// 成功驗證后,$ret 為 true
$ret = validate(UsersValidate::class)->batch(true)->check($data);
} catch (ValidateException $e) {
dump($e->getError());
}
}
......
~~~
一個完整的驗證器代碼如下:
~~~
<?php
declare (strict_types = 1);
namespace app\test\validate;
use think\Validate;
use app\test\model\Users;
class UsersValidate extends Validate
{
/**
* 定義驗證規則
* 格式:'字段名' => ['規則1','規則2'...]
*
* @var array
*/
protected $rule = [
// 'name'=>['require',"unique:users"] ,//unique 會自動把 當前的記錄排除掉
// 'name'=>['require',"unique:users,name,1,id"] ,
'name|用戶名' => 'available_name:admin|require',
'email' => 'email',
];
/**
* 定義錯誤信息
* 格式:'字段名.規則名' => '錯誤信息'
*
* @var array
*/
protected $message = [
'name.require' => '名字是必須的',
'name.available_name' => '該用戶名不可用',
];
protected $scene = [
'add' => ['name'],
'edit' => ['email'],
];
// 自定義驗證規則
public function available_name($value, $rule, $data=[])
{
// 保留用戶名
if ($rule == $rule) return false;
// 已存在用戶,返回 false,即不通過驗證
$user = Users::where('name', '=', $value)->find();
return $user === null ? true : false;
}
}
~~~
- 搭建ThinkPHP6的開發環境
- 配置ThinkPHP6
- 必要的基礎知識(basic)
- MVC開發模式
- 控制器(controller)
- 數據庫(database)
- 模型(model)
- 模型關聯(relation)
- 視圖(view)
- Session
- Cookie
- 緩存(cache)
- 上傳(upload)
- 驗證器(validate)
- 驗證碼(captcha)
- 命令行(command)
- 服務器部署(deploy)
- 數據備份(backup)
- 數據同步(synchronization)
- 訂閱服務(subscribe)
- PHP 易混淆知識點
- 助手函數
- MySQL規范
- Redis 規范
- office插件 phpoffice
- 拼音插件 pinyin
- 日期插件 datetime
- 消息插件 amqp
- 產品部署環境的搭建
- PDF 等雜項處理
- 文件上傳
- 常用擴展
- flc/dysms
- 使用示例 ①
- 使用示例 ②
- qiniu/php-sdk
- 簡介
- 使用示例
- 使用示例 2 ②
- liliuwei/thinkphp-jump
- 擴展介紹
- 下載擴展
- 使用方法
- topthink/think-captcha
- 安裝擴展
- 驗證碼顯示
- 更換驗證碼
- 驗證碼校驗
- 驗證碼配置
- 自定義驗證碼
- phpoffice/phpspreadsheet
- 數據寫入表格
- 讀取表格數據
- topthink/think-queue
- 安裝
- 自定義函數
- 任務類
- 帶有日志的任務類