??Validator 驗證器 和 常用方法

v1.2.7
版本
2025-04-08
版本更新時間
59
安裝
10
star
Jeckleee/Tools
一些常用工具:
- 數(shù)據(jù)驗證 : 總是記不住驗證器的規(guī)則,每次都得查詢文檔,所以本工具提供了一個符合直覺的驗證器,使用鏈?zhǔn)秸{(diào)用添加規(guī)則,方便記憶和使用
- 常用Function :封裝了一些常用的方法
安裝
composer require jeckleee/tools
配置
//配置文件: config/plugin/jeckleee/tools/app.php
return [
'enable' => true,
// 定義驗證失敗以后拋出的異常,webman框架建議使用 support\exception\BusinessException::class
'exception' => Exception::class,
// 定義驗證失敗的錯誤碼
'exception_code' => 500,
//驗證失敗錯誤如何返回(immediate,collective)
//immediate:立即返回,只要驗證出現(xiàn)錯誤,立即拋出當(dāng)前錯誤字段的異常信息,不再驗證剩余的字段
//collective:集中返回,驗證全部字段,收集所有異常,驗證結(jié)束后在異常$e->getMessage()中返回錯誤字段的列表,json字符串形式
'error_return_mode' => 'immediate',
];
查看所有支持的驗證規(guī)則
use Jeckleee\Tools\Validator
echo json_encode(Validator::$showAllRules);
//此工具已經(jīng)收集了大多數(shù)的常用規(guī)則,歡迎大家提交pr補充新的規(guī)則
驗證規(guī)則 | 說明 |
---|---|
required | 字段必填,可設(shè)置一個默認值 |
ifExisted | 對字段進行判斷,如果字段存在,則進行驗證 |
strTrim | 去除字段兩端的空格、制表符、換行符等 |
strLength | 字段的值知必須指定范圍的長度 |
strStartWith | 字段的值必須以指定的字符串開始 |
strEndWith | 字段的值必須以指定的字符串結(jié)尾 |
strAlpha | 字段的值只能由字母組成 |
strAlphaNum | 字段的值只能由字母和數(shù)字組成,$type=true時要求必須同時包含字母和數(shù)字 |
betweenNumber | 字段必須在指定范圍內(nèi) |
cmpNumber | 是betweenNumber方法的補充,允許的符號: >,<,>=,<=,!=,= |
isNumber | 字段的值必須是數(shù)字(int or float) |
isInt | 字段的值必須是整數(shù) |
isFloat | 字段的值必須是小數(shù),傳入?yún)?shù)控制小數(shù)位數(shù) |
inArray | 字段的值必須在數(shù)組中 |
notInArray | 字段的值必須不在數(shù)組中 |
isArray | 字段的值必須是數(shù)組 |
isEmail | 字段的值必須是郵箱 |
isMobile | 字段的值必須是手機號 |
isDateTimeInFormat | 字段的值必須是指定格式的時間字符串(Ymd-His等) |
isIdCard | 字段的值必須是身份證號 |
isUrl | 字段的值必須是網(wǎng)址 |
isIp | 字段的值必須是IP地址(ipv4 or ipv6) |
isBool | 字段的值必須是布爾值,為 "1", "true", "on" and "yes" 返回 TRUE,<br/>為 "0", "false", "off" and "no" 返回 FALSE |
isJson | 字段的值必須是一個json字符串,允許傳入?yún)?shù)將其轉(zhuǎn)為Array |
withRegex | 使用正則表達式驗證字段 |
使用場景1:驗證表單提交的數(shù)據(jù)
use Jeckleee\Tools\Validator
$post=['name'=>'jeckleee','password'=>'123456','email'=>'jeckleee@qq.com','age'=>18];
//驗證一組數(shù)據(jù)
$data=Validator::array($post,[
//只有寫在此數(shù)組中的字段才會驗證并存儲到$data中
Validator::field('name')->required()->strTrim()->strLength(3,32)->verify('請?zhí)顚懻_的用戶名'),
//使用自定義正則表達式驗證
Validator::field('password')->required()->withRegex('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/')->verify('要求密碼必須包含大寫字母、小寫字母、數(shù)字和特殊字符'),
Validator::field('email')->required()->isEmail()->verify('請?zhí)顚懻_的郵箱'),
//不驗證score字段,如果字段不存在則返回["score"=>null]
Validator::field('score')->verify(),
//存在則驗證,如果字段不存在則不驗證,也不會出現(xiàn)在最終的數(shù)據(jù)中
Validator::field('score')->ifExisted()->isInt()->betweenNumber(0,100)->verify('請?zhí)顚懻_的分數(shù)'),
]);
//$data=['name'=>'jeckleee','password'=>'123456','email'=>'jeckleee@qq.com','score'=>null]; //age字段不會出現(xiàn)在$data中
// 按需使用 extract 函數(shù)將關(guān)聯(lián)數(shù)組轉(zhuǎn)換為變量
extract($data);
// 現(xiàn)在可以使用這些變量了
echo $name; // 輸出: jeckleee
echo $password; // 輸出: 123456
echo email; // 輸出: jeckleee@qq.com
驗證一個字段
//驗證一個字段
$data=Validator::one($post,[
Validator::field('age')->required()->isInt()->betweenNumber(1,120)->verify('請?zhí)顚懻_的年齡'),
]);
echo $data; //$data=18
自定義驗證規(guī)則
//自定義驗證方法,只有回調(diào)方法返回(bool)true時,才驗證通過,否則驗證失敗
$data=Validator::one($post,[
Validator::field('age')->fun(function ($value){
if ($value<18){
return false;
}
return true;
})->verify('年齡不能小于18歲'),
]);
自定義驗異常和錯誤碼
//自定義驗證失敗的異常
$data=Validator::array($post,[
//......省略
],MyException::class);
//如果不定義異常類,則使用配置文件中定義的異常
//三種異常定義的區(qū)別:
//1.使用配置文件中定義異常和錯誤碼
$data=Validator::array($post,[
Validator::field('name')->required()->verify('請?zhí)顚戀~號'),
//......省略
]);
//2.在使用array()或者one()方法時定義異常和錯誤碼,會覆蓋配置文件中定義的異常
$data=Validator::array($post,[
Validator::field('name')->required()->verify('請?zhí)顚戀~號'),
//......省略
],MyException::class);
//3.在規(guī)則中的->verify()方法中定義的錯誤碼優(yōu)級最高,會覆蓋之前所有的定義
$data=Validator::array($post,[
Validator::field('name')->required()->verify('請?zhí)顚戀~號',12001),
Validator::field('age')->required()->isInt()->betweenNumber(1,120)->verify('請?zhí)顚懻_的年齡',12002),
//......省略
]);
一個使用示例
use Jeckleee\Tools\Validator as V;
use support\Request;
class PostController extends BaseController
{
/**
* @Notes: 保存數(shù)據(jù)
* @Name save
* @return \support\Response
* @author: -
* @Time: 2024/2/5 15:06
*/
public function save(Request $request): \support\Response
{
try {
$input = V::array($request->all(), [
V::field('title')->required()->verify('請?zhí)顚憳?biāo)題'),
V::field('content')->required()->verify('請?zhí)顚憙?nèi)容'),
V::field('category_id')->required(1)->isInt()->inArray([1,2,3,4])->verify('請選擇正確的分類'),
V::field('status')->required(-1)->inArray([-1, 1, 2, 9])->verify('請選擇正確的狀態(tài)'),
]);
$post = Post::create($input);
$this->msg = '保存成功';
} catch (BusinessException $exception) {
$this->code = $exception->getCode() ?: 300;
$this->msg = $exception->getMessage();
$this->status = 'error';
}
return json($this->getFormatApiData());//getFormatApiData是一個我自己的自定義方法,返回格式化后的數(shù)據(jù)或者錯誤
}
使用場景2: 驗證變量是否正確,返回(bool) TURE or FALSE
use Jeckleee\Tools\Validator as V;
$phone='123456789';
if (V::var($phone)->isMobile()->check()){
echo '手機號碼正確';
}else{
echo '手機號碼不正確'
}
注意事項
- 暫無