0
点赞
收藏
分享

微信扫一扫

Laravel 自定义验证器


想必各位在想。

[
'title' => 'required|max:2',
'body' => 'required',
]

验证规则如上

我们如何自定义这些规则呢

Laravel 自定义验证器_laravel

boot下面新增这些方法

public function boot()
{


parent::boot();

//验证正整数,
Validator::extend('is_positive_integer', function ($attribute, $value, $parameters, $validator) {
return is_numeric($value) && is_int($value + 0) && ($value + 0) > 0;
});
//验证0和1的状态
Validator::extend('is_status_integer', function ($attribute, $value, $parameters, $validator) {
return is_numeric($value) && is_int($value + 0) && in_array(($value + 0), [0, 1]);
});
//验证是否为数组并且在里面的值必须是正整数
Validator::extend('is_array_integer', function ($attribute, $value, $parameters, $validator) {
if (is_array($value) && count($value) > 0) {
foreach ($value as $v) {
if (!is_numeric($value) || !is_int($value + 0) || ($value + 0) <= 0) {
return false;
}
}
} else {
return false;
}
return true;
});
//验证pid >=0
Validator::extend('is_pid_integer', function ($attribute, $value, $parameters, $validator) {
return is_numeric($value) && is_int($value + 0) && ($value + 0) >= 0;
});


}

记得导入包哦

use Illuminate\Support\Facades\Validator;

验证器修改下

public function test(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|max:2|is_positive_integer',
'body' => 'required',
], [
'title.required' => "请输入标题",
'title.max' => "标题最大长度不能超过2个字符",
'title.is_positive_integer' => "请设置为正整数的标题",
]);

if ($validator->fails()) {
return $validator->errors()->messages()['title'][0];
}

return "hello world";

// 博客文章验证通过...
}

Laravel 自定义验证器_数组_02

我们一共传递了四个参数其他的三个没有用到

可以打印看下

Validator::extend('is_positive_integer', function ($attribute, $value, $parameters, $validator) {
dd([$attribute, $value, $parameters, $validator]);
return is_numeric($value) && is_int($value + 0) && ($value + 0) > 0;
});

Laravel 自定义验证器_php_03

 通常情况下


$attribute



$value


就够了 、


$validator 有完整的信息。

举报

相关推荐

0 条评论