【问题标题】:how to get the value of parameter passed in custom validation rule laravel 5如何获取自定义验证规则laravel 5中传递的参数值
【发布时间】:2015-09-11 12:45:02
【问题描述】:
The custom validation rule is :

Validator::extend('greater_than', function($attribute, $value, $parameters) {
    if (isset($parameters[0])) {
        return intval($value) > intval($parameter[0]);
    } else {
        return false;
    }
}

max_occupancy rule would then be:

'max_occupancy' => 'required|integer|max:100|greater_than:base_occupancy'

但返回的“$parameters”数组是: 数组:1 [▼ 0 => "base_occupancy"]。 所以我没有得到 base_occupancy 的值来检查“大于”条件。

【问题讨论】:

  • base_occupancy 是表单中的一个字段吗?
  • class AddRoomRequest extends Request { public function rules() { return [ 'name' => 'required|min:2|max:1000', 'base_occupancy' => 'required|integer|min: 0|max:100', 'max_occupancy' => '必需|整数|max:100|greater_than:base_occupancy' ]; } }
  • 是表单请求的吗?
  • 是的,我创建了一个请求“AddRoomRequest”,其中包含一些规则并有 2 个参数,我试图将其关联起来,即............ 'base_occupancy' => 'required|integer|min:0|max:100', 'max_occupancy' => 'required|integer|max:100|greater_than:base_occupancy'

标签: laravel-5 custom-validators


【解决方案1】:

使用$validator->getData()。它将返回一个键值数组,其中键是表单输入名称,值是它们的值。

在你的情况下,像这样修复:

Validator::extend('greater_than', function($attribute, $value, $parameters, $validator) {
    $all_form_data = $validator->getData();
    if (isset($all_form_data[$parameters[0]])) {
        return intval($value) > intval($all_form_data[$parameters[0]]);
    } else {
        return false;
    }
}

【讨论】:

    猜你喜欢
    • 2015-01-26
    • 2018-07-29
    • 2016-12-23
    • 2015-08-05
    • 2015-06-02
    • 2017-12-01
    • 2017-04-11
    • 2018-02-18
    • 1970-01-01
    相关资源
    最近更新 更多