laravel-validation

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