Vin*_*rat 5 validation laravel
Suppose we have the following form data:
{age: 15, father: "John Doe"}
Run Code Online (Sandbox Code Playgroud)
我们希望在father基于同一项目的其他数据验证字段背后有一些复杂的逻辑(对于此示例,我们希望验证父亲在年龄 < 18 时至少有 5 个字符)。
这可以这样做:
Standard validation rules: ['age': 'required|integer']
$validator->sometimes('father', 'required|min:5', function($data) {
return $data['age'] < 18;
});
Run Code Online (Sandbox Code Playgroud)
现在,我们想用一个项目列表来做同样的事情。所以现在,我们有以下表单数据:
[
{age: 25, },
{age: 15, father: "John Doe"},
{age: 40, },
]
Run Code Online (Sandbox Code Playgroud)
通用验证规则现在看起来像这样:
['items.*.age': 'required|integer']
Run Code Online (Sandbox Code Playgroud)
我现在的问题是轻松表达sometimes每个项目father字段的规则,这取决于项目的age字段。
$validator->sometimes('items.*.father', 'required|min:5', function($data) {
// Does not work anymore: return $data['age'] < 18;
// Any way to know which item we are dealing with here?
});
Run Code Online (Sandbox Code Playgroud)
我能想到的一种方法是循环验证器after回调中的项目。但这似乎不太优雅:(
无法以sometimes()您需要的方式开始工作。sometimes()不会“循环”数组项,它被调用一次。
我想出了一种替代方法,虽然并不完美,但也许您会发现它很有用。
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
Validator::extend('father_required_if_child', function ($attribute, $value, $parameters, $validator) {
$childValidator = Validator::make($value, [
'age' => 'required|integer'
]);
$childValidator->sometimes('father', 'required|min:5', function($data) {
return is_numeric($data['age']) && $data['age'] < 18;
});
if (!$childValidator->passes()) {
return false;
}
return true;
// Issue: since we are returning a single boolean for three/four validation rules, the error message might
// be too generic.
// We could also ditch $childValidator and use basic PHP logic instead.
});
return [
'items.*' => 'father_required_if_child'
];
}
Run Code Online (Sandbox Code Playgroud)
很想知道如何改进这一点。
| 归档时间: |
|
| 查看次数: |
1849 次 |
| 最近记录: |