首页 > 解决方案 > 如何对 2 个字段产生一个验证错误

问题描述

我有 2 个用于邮政编码主要和次要的字段。

<input type="text" name="postal01">
<input type="text" name="postal02">

我想验证添加的两个字段的数字和大小。我想要做的是将一个字段的验证错误显示为 postal_cd,而不是每个字段错误。

我曾在请求类扩展 FormRequest 中尝试过。

class MemberRequest extends FormRequest
{
  public function all($keys = null)
  {
    $result = parent::all($keys);

    if($this->filled('postal01') && $this->filled('postal02')) {
        $results['postal_code'] = $this->input('postal01') . $this->input('postal02');
    }
    return $result;
}

然而它并没有像我预期的那样工作。

我该如何处理这种情况?

标签: laravel-5

解决方案


您可以使用After Validation Hook。将以下内容添加到您的表单请求中:

/**
* Configure the validator instance.
*
* @param  \Illuminate\Validation\Validator  $validator
* @return void
*/
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if($validator->errors()->has('postal01') || $validator->errors()->has('postal02')) {
            $validator->errors()->add('postal_cd', 'Please enter a postal code');
        }
    });
}

...然后将其显示在刀片​​上:

{{ $errors->first('postal_cd') }}

推荐阅读