laravel自定义验证

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

2、全局自定义方法
在 app/Providers/AppServiceProvider.php
use AppValidationsCustomValidation;
 
public function boot()
{
new CustomValidation();
}

3、在/resources/lang/en/validation.php定义返回错误提示

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

namespace AppValidations;

use IlluminateSupportFacadesValidator;

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 ules中可以写入
'video_ids' => 'string|nullable|max_id',

 
https://upeng.github.io/blog/2017/10/18/laravel-validator/



原文地址:https://www.cnblogs.com/agang-php/p/10491760.html