我正在尝试从表单输入中验证数组。我将需要将我的字段值之一传递给该附加字段的规则列表中的另一个表单字段的自定义Rule类。如何做到这一点?
这里是进一步的解释。验证field1之后,我需要将该值传递给field2字段CustomRule类。
<div class="container">
<div class="category">Category 1</div>
<div class="category">Category 2</div>
<div class="category">Category 3</div>
<div class="category">Category 4</div>
<div class="category">Category 5</div>
<div class="category">Category 6</div>
</div>
<div class="container">
<div class="category">Category 1</div>
<div class="category">Category 2</div>
<div class="category">Category 3</div>
</div>
<div class="container">
<div class="category">Category 1</div>
<div class="category">Category 2</div>
</div>
答案 0 :(得分:0)
使用验证扩展程序会起作用:
// register the rule in AppServiceProvider.php
Validator::extend('custom_rule', function ($attribute, $value, $parameters, $validator) {
// field1 is accessible in $parameters. Add your custom validation logic here, for example:
return $value < $parameters[0];
});
然后将field1
的值作为参数传递给规则:
public function rules()
{
$rules = [
'array' => ['array'],
'array.*.field1' => [
'required',
'integer',
'min:1',
'distinct',
]
];
foreach ($this->array as $idx => $val) {
$rules['array.' . $idx . '.field2'] = [
'required',
'integer',
'min:1',
'custom_rule:' . $val['field1'],
];
}
return $rules;
}
使用规则对象:
class CustomRule implements Rule
{
public $field1;
public function __construct($field1)
{
$this->field1 = $field1;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return $value < $this->field1;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute must be less than field1.';
}
}
// loop the array elements
foreach ($this->array as $idx => $val) {
$rules['array.' . $idx . '.field2'] = [
'required',
'integer',
'min:1',
new CustomRule($val['field1']),
];
}