Laravel,如何创建验证多个输入的规则

时间:2018-12-26 19:36:30

标签: laravel-5.7

我正在使用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);

        }

1 个答案:

答案 0 :(得分:1)

我刚刚在构造函数上传递了参数。非常基本的东西

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!';
    }
}