Laravel 5.6:将不同的表单字段值传递给另一个字段的验证

问题描述 投票:0回答:1

我正在编写自定义验证规则。在我的表单中,我使用带有名为“my-event”的验证组的规则验证字段。我的一条规则是,如果选中一个名为“other”的复选框,则需要填写文本字段“other”。

我的请求根据这些规则得到验证:

EventRequest.php

 public function rules()
    {
        return [
            'my-event.event-types' => 'required'
            'my-event.event-type-other' => [
                'string', new CheckboxIsValid($checkboxArray)
            ],
        ];
    }

CheckboxIsValid是我编写的一个帮助类,它实现了Laravel的规则:

class CheckboxIsValid implements Rule
{

    public $checkboxArray;

    public function __construct($checkboxArray)
    {
        $this->checkboxArray = $checkboxArray;
    }

    public function passes($attribute, $value)
    {
        if(in_array('other', $this->checkboxArray)) {
            if($value) {
                return true;
            }
        }
        return false;
    }

}

这将检查“其他”是否在我的已选中复选框数组中。我想传递my-event.event-types的价值。我该怎么做呢?

laravel validation
1个回答
0
投票

EventRequest.php扩展了FormRequest,它扩展了Request,它将允许访问其他表单字段值:

$this->validationData()

我在EventRequest.php中访问过这个,如下所示:

// Instantiate it in case form is submitted without any event types

$eventTypes = [];

if(isset($this->validationData()['my-event']['event-types'])){
            $eventTypes = $this->validationData()['my-event']['event-types'];
        }

然后这可以传递到我的规则中:

 'my-event.event-types-other' => [
            new CheckboxIsValid($teachingMethods, 'other')
        ],

在CheckboxIsValid的构造函数中:

public $checkboxArray;
public $field;

public function __construct($checkboxArray, $field)
{
    $this->checkboxArray = $checkboxArray;
    $this->field = $field;
}
© www.soinside.com 2019 - 2024. All rights reserved.