S_R
S_R

Reputation: 1998

Laravel validation min and regex being outputted to the same message

I'm having a bit of a weird issue and i'm not quite sure why its happening or if i'm just missing something.

I have multiple validation rules on a input 'postcode' field, like so

'postcode' => [
                'required',
                'min:5',
                'max:8',
                'regex:/^[a-z]/i'
              ],

And i've also wrote custom messages for the rules like so

return [
     'postcode.min' => 'The postcode must be at least 5 characters',
     'postcode.regex' => 'Sorry, the postcode must start with a letter',
];

All of my errors are being looped and displayed like this

<div class="error-block {{ (count($errors) > 0) ? '' : 'hide' }}">
    <div class="col-12">
        <ul>
            @if(count($errors) > 0)
                @foreach($errors->all() as $error)
                    <li>{{$error}}</li>
                @endforeach
            @endif
        </ul>
    </div>
</div>

But when both rules are hit for the postcode, for example with the input '123', then it pushes both errors out on the same line, but all other errors show correctly, like this

  • The postcode must be at least 5 characters,Sorry, the postcode must start with a letter.
  • The username field is required.
  • The address line 1 field is required.

Why is laravel pushing the min and regex rule messages out on the same line?

Upvotes: 0

Views: 1181

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 14520

As described in the docs, validation rules should be expressed as a string, with different rules for a single input separated by a pipe |. The set of inputs to be validated should be an array, but not the rules themselves.

In your case, for the postcode input:

'postcode' => 'required|min:5|max:8|regex:/^[a-z]/i',

Upvotes: 1

kamote ulalo
kamote ulalo

Reputation: 162

That means your $error is an array. if you want to list all error as new line, check if the error is also an array or is not an array.

 @if(count($errors) > 0)
        @foreach($errors->all() as $error)
            @if(is_string($error))
               <li>{{$error}}</li>
           @else
                @foreach( $error as $newBreakdown)
                     <li>{{$newBreakdown}}</li>
                @endforeach
           @endif
        @endforeach
    @endif

Upvotes: 0

Related Questions