Laravel 验证数组并在彼此之间传递字段值
我正在尝试从表单输入验证数组。我需要将一个字段的值传递给该附加字段的规则列表中附加表单字段的自定义规则类。如何做到这一点 下面是进一步的解释。验证field1后,我需要将该值传递给field2 field CustomRule类Laravel 验证数组并在彼此之间传递字段值,laravel,Laravel,我正在尝试从表单输入验证数组。我需要将一个字段的值传递给该附加字段的规则列表中附加表单字段的自定义规则类。如何做到这一点 下面是进一步的解释。验证field1后,我需要将该值传递给field2 field CustomRule类 public function rules() { return [ 'array' => ['array'], 'array.*.field1' => [ 'required',
public function rules()
{
return [
'array' => ['array'],
'array.*.field1' => [
'required',
'integer',
'min:1',
'distinct',
],
'array.*.field2' => [
'required',
'integer',
'min:1',
new CustomRule(),
],
];
}
使用验证扩展将起到以下作用:
// 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];
});
使用规则对象:
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']),
];
}
类CustomRule实现规则
{
公共领域1;
公共功能构造($field1)
{
$this->field1=$field1;
}
/**
*确定验证规则是否通过。
*
*@param string$属性
*@param混合$value
*@returnbool
*/
公共函数传递($attribute,$value)
{
返回$value<$this->field1;
}
/**
*获取验证错误消息。
*
*@返回字符串
*/
公共功能消息()
{
返回“该:属性必须小于field1”;
}
}
//循环数组元素
foreach($此->数组为$idx=>$val){
$rules['array..$idx..field2']=[
“必需”,
“整数”,
"min:1",,
新的CustomRule($val['field1']),
];
}
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']),
];
}