Laravel使用闭包验证 [英] Laravel validation Using Closures
本文介绍了Laravel使用闭包验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Laravel 5.4开发我正在尝试Laravel文档中的示例:
Developing with Laravel 5.4 I am trying the example from Laravel documentation:
$validator = Validator::make($request->all(), [
'title' => [
'required',
'max:255',
function($attribute, $value, $fail) {
if ($value === 'foo') {
return $fail($attribute.' is invalid.');
}
},
],
]);
我收到此错误:
关闭类的对象无法转换为字符串
Object of class Closure could not be converted to string
为什么?
推荐答案
在5.4中,如果您不希望使用闭包,则可以在验证规则之后通过它,如下所示:
In 5.4 if you wan't a closure you can pass it after the validation rules, like this:
$validator = Validator::make($request->all(), [
'title' => ['required', 'max:255'],
]);
$validator->after(function ($validator) {
if ($request->get('field') === 'foo') {
$validator->errors()->add('field', 'Field is invalid.');
}
});
if ($validator->fails()) {
//
}
这篇关于Laravel使用闭包验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文