假设我们有一个名为(a,b,c,d)的输入字段数组,我们需要验证它们之间的某种关系。
为简单起见,我们假设它们都是数字,我们需要验证总和a + b
大于c + d
。
其他示例可以验证多个不重叠的日期范围。
我们如何定义验证规则以及哪些字段应收到错误?
已经有针对这种情况的设计模式了吗?
答案 0 :(得分:1)
<?php
// Laravel now has a function called `prepareForValidation` in request class
// applicable for Laravel version 5.6+. You can use that to validate :
namespace App\Http\Requests;
use App\Http\Requests\Request;
class YourCustomRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'a' => 'required|numeric',
'b' => 'required|numeric',
'c' => 'required|numeric',
'd' => 'required|numeric',
// Validate if sum_a_b value is greater than sum_c_d value
'sum_a_b' => 'gt:sum_c_d'
];
}
protected function prepareForValidation()
{
// Add new fields with values representing the sums
$request->merge([
'sum_a_b' => $this->input('a') + $this->input('b'),
}
}
// And then in your controller's post action
public function store(YourCustomRequest $request)
{
// Do actions when vaidation is successful
}