首页 > 解决方案 > Laravel,如何创建验证多个输入的规则

问题描述

我正在使用 Laravel 5.7,我需要检查三个输入的总和是否在一个范围内。

//I don't want to add if statement here to check if the sum of the three inputs are within range.

// I was thinking in a scenario like below: 
//where CheckSum would be a custom rule. Is that possible?      

 $validacoes = [

            'comprimento' => ['required', new CheckSum($request->comprimento, $request->largura, $request->altura),
            'largura' => 'required|min:11|max:105',
            'altura' => 'required|min:2|max:105'


        ];


     $validator = Validator::make($request->all(), $validacoes);



        if ($validator->fails()) {

            $erro = $validator->errors()->first();

            return response()->json(["data" => [ "erro" => $erro ]], 400);

        }

标签: laravel-5.7

解决方案


我只是在构造函数上传递了参数。很基础的东西

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CheckDimension implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */


     private $width;
     private $length;
     private $height;

    public function __construct($height, $width, $length)
    {
        $this->height  = $height;
        $this->width = $width;
        $this->length = $length;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {

        $sum = $this->height + $this->length + $this->width;

        if($sum < 29 || $sum > 200){

            return false;
        }
        else {
            return true;
        }

    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'out of range!';
    }
}

推荐阅读