提问者:小点点

使用Laravel有条件地验证字段


我对Laravel有以下验证规则:

return [
    'offer_type' => 'required|in:permanent,temporary',
    'start_date' => 'required_if:offer_type,temporary|date_format:d/m/Y',
    'end_date' => 'required_if:offer_type,temporary|date_format:d/m/Y|after:start_date',
];

基本上,如果offer_type临时,则需要start_dateend_date,并且必须遵循d/m/Y格式。另外,end_date必须在start_date之后。

如果offerType永久的,则不需要验证start_dateend_date,因为它们甚至没有被使用。

我遇到的问题是,如果用户发送如下数据:

  • 报价类型:永久性
  • 开始日期:foo
  • endDate:条形图

然后,Laravel将引发验证错误,即使不需要验证开始日期结束日期,因为报价类型是永久

我怎么能让Laravel只验证start_dateend_date如果offer_type临时

我的(坏)解决方案

我发现解决此问题的唯一方法是执行以下操作:

将上述验证规则更改为以下内容:

return [
    'offer_type' => 'required|in:permanent,temporary',
    'start_date' => 'required_if:offer_type,temporary',
    'end_date' => 'required_if:offer_type,temporary',
];

并将以下代码添加到验证程序:

$validator->after(function (Validator $validator) {
    $data = $validator->getData();
    $failed = $validator->failed();

    if (array_key_exists('offerType', $data) &&
        $data['offerType'] === 'temporary' &&
        array_key_exists('start_date', $data) &&
        array_key_exists('end_date', $data) &&
        !array_key_exists('start_date', $failed) &&
        !array_key_exists('end_date', $failed)
    ) {
        $startDateString = $data['start_date'];
        $endDateString = $data['end_date'];

        $startDate = Carbon::createFromFormat('d/m/Y', $startDateString);
        $endDate = Carbon::createFromFormat('d/m/Y', $endDateString);

        if ($startDate === false) {
            $validator->errors()->add('start_date', 'Start date must be in the format "dd/mm/yyyy"');
        }

        if ($endDate === false) {
            $validator->errors()->add('end_date', 'End date must be in the format "dd/mm/yyyy"');
        }

        if ($startDate !== false && $endDate !== false && $endDate->lt($startDate)) {
            $validator->errors()->add('end_date', 'End date must be after or equal to the start date');
        }
    }
});

共1个答案

匿名用户

我建议你有一个单独的FormRequest类。然后您的规则()将如下所示:

public function rules()
{
    $rules = [
        'offer_type' => 'required|in:permanent,temporary',
        'start_date' => 'required_if:offer_type,temporary',
        'end_date' => 'required_if:offer_type,temporary',
    ];

    if ($this->offer_type == 'permament') {
        $this->getInputSource()->remove('start_date'); // optionally you may remove start_date from request
        $this->getInputSource()->remove('end_date');  // same of end_date
        unset($rules['start_date']); 
        unset($rules['end_date']);
    }

    return $rules;
}

关于表单请求验证的Laravel文档