laravel-validation

webman-tech/laravel-validation
Laravel illuminate/validation for webman
介紹
站在巨人(laravel)的肩膀上使驗(yàn)證器使用更加可靠和便捷
所有方法和配置與 laravel 幾乎一模一樣,因此使用方式完全參考 Laravel文檔 即可
安裝
composer require webman-tech/laravel-validation
使用
所有 API 同 laravel,以下僅對(duì)有些特殊的操作做說明
常規(guī)使用如下:
<?php
namespace app\controller;
use support\Request;
class FooController
{
public function bar(Request $request)
{
$validator = validator($request->post(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return json($validator->errors()->first());
}
return json('ok');
}
}
file/mimeType 相關(guān)的 rule
由于 laravel 的 validation 驗(yàn)證 file/image 等文件時(shí)(包括文件 mimeType)時(shí),都是使用的 Symfony 的 UploadedFile,而 webman 里 $request->file()
得到的是 Webman\UploadFile
,
因此無(wú)法直接使用相關(guān)的 rules
需要使用 webman-tech/polyfill
來(lái)支持
安裝
composer require webman-tech/polyfill illuminate/http
使用
<?php
namespace app\controller;
use support\Request;
use WebmanTech\Polyfill\LaravelRequest;
class FooController
{
public function bar(Request $request)
{
$validator = validator(LaravelRequest::wrapper($request)->all(), [
'file' => 'required|file|image',
]);
if ($validator->fails()) {
return json($validator->errors()->first());
}
return json('ok');
}
}
$request->validate
需要使用 webman-tech/polyfill
來(lái)支持
安裝
composer require webman-tech/polyfill illuminate/http
使用
<?php
namespace app\controller;
use support\Request;
use WebmanTech\Polyfill\LaravelRequest;
class FooController
{
public function bar(Request $request)
{
LaravelRequest::wrapper($request)->validate([
'file' => 'required|file|image',
]);
return json('ok');
}
}
自定義驗(yàn)證規(guī)則
在 config/plugin/webman-tech/laravel-validation/app.php
的 extends
字段中配置即可
配置形式同 Laravel
目前暫未提供 make:rule 的 command,需要自己寫 Rule 類
locale 本地化翻譯需求
支持本地化
需要使用 webman-tech/laravel-translation
來(lái)支持
安裝
composer require webman-tech/laravel-translation
你也可以自行實(shí)現(xiàn)驗(yàn)證錯(cuò)誤消息的本地化實(shí)現(xiàn)
通過修改 config/plugin/webman-tech/laravel-validation/app.php
的 translation
提供一個(gè) Illuminate\Contracts\Translation\Translator
來(lái)實(shí)現(xiàn)
切換 locale
因?yàn)闆]有 Laravel App 的存在,所以不能通過 App::setLocale()
和 App::currentLocale()
來(lái)切換驗(yàn)證器的語(yǔ)言
且由于 webman 建議的多語(yǔ)言是使用的 symfony/translation
,并且全局 locale
函數(shù)也是使用其實(shí)現(xiàn)的
因此本擴(kuò)展基于此原因,已經(jīng)做到了根據(jù) locale()
自動(dòng)切換 validator()
下使用的語(yǔ)言包,無(wú)需開發(fā)手動(dòng)設(shè)置
unique 驗(yàn)證器
unique 依賴數(shù)據(jù)庫(kù),本擴(kuò)展對(duì)已經(jīng)安裝 illuminate/database
了 webman 應(yīng)用自動(dòng)支持
如果不支持,比如報(bào)錯(cuò):Presence verifier has not been set.
時(shí),請(qǐng)手動(dòng)安裝 illuminate/database
原則上不一定強(qiáng)依賴于 Laravel 的 database, TP 的應(yīng)該也是可以的(實(shí)現(xiàn) DatabasePresenceVerifierInterface),目前暫未實(shí)現(xiàn),歡迎PR