tajihiro
tajihiro

Reputation: 2443

How to make one validation error for 2 fields

I have 2 fields for postal code main and sub.

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

I would like to have validation for numeric and size of both fields added. What I want to do is showing validation error for one field as postal_cd, not each field error.

I had tried in a request class extended 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;
}

However it did not work like I expected.

How can I handle this case?

Upvotes: 0

Views: 29

Answers (2)

tajihiro
tajihiro

Reputation: 2443

That was my typo.

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

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

Returned value should have been $result. But it was typo $results['postal_code']. It works.

Upvotes: 0

Mozammil
Mozammil

Reputation: 8750

You can use an After Validation Hook. Add the following to your Form Request:

/**
* 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');
        }
    });
}

... and then to display it on your blade:

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

Upvotes: 1

Related Questions