【问题标题】:Laravel validating. One field must be greater than anotherLaravel 验证。一个字段必须大于另一个字段
【发布时间】:2018-03-19 21:22:26
【问题描述】:

我正在尝试做一些 laravel 验证。

我需要确保该字段的最大租金始终大于最小租金,并提供一条消息让用户知道。

这是我的控制器中的验证码

$this->validate($request, [
        "county" => "required",
        "town" => "required",
        "type" => "required",
        "min-bedrooms" => "required",
        "max-bedrooms" => "required",
        "min-bathrooms" => "required",
        "max-bathrooms" => "required",
        "min-rent" => "required|max4",
        "max-rent" => "required|max4",
      ]);

我没有使用单独的规则方法。这是在控制器内

【问题讨论】:

标签: laravel laravel-5


【解决方案1】:

您可以使用Custom Validation Rule

1。创建规则类

php artisan make:rule RentRule

2。插入你的逻辑

App\Rules\RentRule

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class RentRule implements Rule
{
    protected  $min_rent;

    /**
     * Create a new rule instance.
     *
     * @param $min_rent
     */
    public function __construct($min_rent)
    {
        // Here we are passing the min-rent value to use it in the validation.
        $this->min_rent = $min_rent;         
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // This is where you define the condition to be checked.
        return $value > $this->min_rent;         
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        // Customize the error message
        return 'The maximum rent value must be greater than the minimum rent value.'; 
    }
}

3。使用它

use App\Rules\RentRule;

// ...

$this->validate($request, [
        "county" => "required",
        "town" => "required",
        "type" => "required",
        "min-bedrooms" => "required",
        "max-bedrooms" => "required",
        "min-bathrooms" => "required",
        "max-bathrooms" => "required",
        "min-rent" => "required|max4",
        "max-rent" => ["required", new RentRule($request->get('min-rent')],
      ]);

旁注

我建议您使用Form Request 类从控制器中提取验证逻辑并解耦您的代码。这将使您拥有只有一个职责的类,从而更容易测试和更清晰地阅读。

【讨论】:

  • 不错且完整的答案。谢谢。
  • 我只想使用 FormRequest 来实现这一点。这可能吗?
  • @JunaidQadirShekhanzai 当然可以。唯一的区别是将值传递给您的自定义规则的方式 - 而不是:"max_rent" => ["required", new RentRule($request->get('min_rent')],,您应该这样做:"max_rent" => ["required", new RentRule($this->min_rent)],。如果您对此有任何疑问,请告诉我。
【解决方案2】:

我们可以使用请求中的参数作为验证规则的一部分。这可以在一个字段必须大于另一个字段的情况下使用。下面的代码是一个检查max-rent应该大于min-rent.的例子,在这种情况下验证规则numeric重要的是我们检查数字,否则它会检查字符数。

$request->validate([
    "min-rent" => "required|numeric|max:9999",
    "max-rent" => "required|numeric|min:{$request->input('min-rent')}|max:99999",
]);

【讨论】:

猜你喜欢
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 1970-01-01
  • 2015-11-09
  • 2020-02-17
  • 1970-01-01
  • 2018-09-04
相关资源
最近更新 更多