如何在Laravel的FormRequest中针对多个值进行验证?

时间:2019-10-28 09:25:30

标签: laravel validation

我正在将两个字段传递给我的API max_durationmin_duration,并且我正在使用Laravel的FormRequest执行验证。这是我的 RecommendationRequest.php 类:

{
    /**
     * 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 [
            "max_duration" => ["integer", new ValidateMaxDuration],
            "min_duration" => ["integer", new ValidateMinDuration]
        ];
    }

}

这是我的ValidateMaxDuration.php规则,我想验证max_duration的值是否高于min_duration的值。我该怎么办?

class ValidateMaxDuration implements Rule
{
    private $minDuration;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        // $this->minDuration = $minDuration;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // logic done here to validate max value
        // return $value[0] < $value[1] ? false : true; 
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return "Max duration must be a higher value than min duration.";
    }
}

0 个答案:

没有答案