laravel自定義驗證

一、在控制器中直接寫驗證
$this->validate($request, [
'video_ids' => [
function($attribute, $value, $fail) {
$ids = explode(',', $value);
foreach ($ids as $id) {
if ($id > 2147483647) {
$fail(':id max is 2147483647!');
}
}
}
]
]);

二、全局自定義方法
在 app/Providers/AppServiceProvider.php
use App\Validations\CustomValidation;
 
public function boot()
{
new CustomValidation();
}

三、在/resources/lang/en/validation.php定義返回錯誤提示

return [
'max_id' => 'max id is 2147483647'
];
四、在app/Validation/CustomValidation.php
<?php
/**
* Created by PhpStorm.
* User: ganga
* Date: 2019/3/7
* Time: 下午8:00
*/

namespace App\Validations;

use Illuminate\Support\Facades\Validator;

class CustomValidation
{
public function __construct()
{
$this->maxId();
}

public function maxId()
{
Validator::extend('max_id', function ($attribute, $value, $parameters, $validator) {
$ids = explode(',', $value);
foreach ($ids as $id) {
if ($id > 2147483647) {
return false;
}
}
return true;
});
}
}

5\rules中能夠寫入
'video_ids' => 'string|nullable|max_id',

 
https://upeng.github.io/blog/2017/10/18/laravel-validator/
相關文章
相關標籤/搜索