如何在Laravel中验证输入一致性(或字段/字段组合之间的关系)? [关闭]

问题描述 投票:0回答:1

假设我们有一个名为(a,b,c,d)的输入字段数组,我们需要验证它们之间的某种关系。

为简单起见,我们假设所有这些都是数字,我们需要验证总和a + b是否大于c + d

其他示例可以验证多个非重叠日期范围。

我们如何定义验证规则以及哪些字段应该收到错误?

对于这种情况,是否已经存在设计模式?

php laravel validation input
1个回答
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
}
© www.soinside.com 2019 - 2024. All rights reserved.