Laravel中Validator的验证扩展

虽然Laravel提供一套包括正则匹配在内的完善的验证机制,但你一定会遇到使用规则解决不了的验证,比如数据库验证,这时需要用到Validator的验证扩展。

(1)使用静态方法:Validator::extend
(2)使用对象调用:$validator->addExtension

下面是验证HTTP提交的商品分类信息的例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use \Illuminate\Http\Request;
use App\Exceptions\MyValidationException;
use App\GoodsCategory;

class GoodsValidator
{

public static function validate(Request $request, $final = false)
{
$messages = [
//'category_id.required' => ':attribute 输入不正确!',
'category_id.required' => '抱歉,您输入的商品分类信息为空',
'category_id.min' => '抱歉,您输入的商品分类信息长度有误',
'category_id.category_id_check' => '抱歉,您输入的商品分类信息不存在',
];

$rules = [
'category_id' => 'required|min:4|category_id_check',
];

Validator::extend('category_id_check', function($attribute, $value, $parameters) {
return GoodsCategory::where('category_id', $value)->exists();
});

$validator = Validator::make($request->all(), $rules, $messages);
/*
$validator->addExtension('category_id_check', function($attribute, $value, $parameters) {
return GoodsCategory::where('category_id', $value)->exists();
});
*/
if ($validator->fails()) {
$messageBag = $validator->messages();
$messageArr = $messageBag->getMessages();
print_r($messageArr);
}
}

}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :