2
votes

How can I validate an array value in Laravel 5.1? Each values of the array should be validated. Number of array values may increase or decrease. But the name will be same. My sample input will be like,

emails[] = '[email protected]',
emails[] = '[email protected]',

I gave the validation rule like,

'emails' => 'required|email'

But when I give more than one values, it returns email invalid error because the email input is array. How can I validate this? Should I write custom rule?

Based on this answer I have tried something like,

$validator->each('emails', 'required|email')

But not working.

3
This questions is already answered here: stackoverflow.com/questions/33368759/…shock_gone_wild
My input array format is different. I do not have any sub arrays. So I have tried like, $validator->each('emails', 'required|email'). Still not working.Joel James
you have missed the point for declaring 'emails' => 'array' in your rules.. I will show you an example in an answershock_gone_wild

3 Answers

2
votes

If you are trying to validate an array value.
You can use in the validation place like below,

    'email.*' => 'required|email'        

If it is an object like,

    {
      'email' : [
                  {
                    'email' : '[email protected]'
                  },
                  {
                    'email' : '[email protected]'
                  }
                 ]
    }

Then you need to use like below,

   'email.*.email' => 'required|email'

Thse are the best way of validate an array elements.

1
votes

Here is a basic example of what your are looking for ( hopefully )

This is a simple blade file that just shows a form with two email fieds and a short error display:

@if($errors->any())
    @foreach($errors->all() as $error)
        <p>{{ $error }}</p>
    @endforeach
@endif

<form action="{{ route('emails.store') }}" method="POST">
    {{ csrf_field() }}
    <input name='emails[]'>
    <input name="emails[]">
    <input type="submit" name="submit">
</form>

Inside the store method of my controller I put:

public function store(Request $request)
{
    $validator = \Validator::make($request->all(), [
        'emails' => 'array',
        // your other rules here
    ]);

    $validator->each('emails', 'required|email');

    if($validator->fails()) {
        return back()->withErrors($validator->errors());
    }

    dd('success');
}

This is working as expected and validates all emails[] fields

0
votes

You might want to try this from the documentation https://laravel.com/docs/5.2/validation#validating-arrays