2

If I have an array validation rule, how can I check if all the items in the array is a valid email? I'm using this: https://laravel.com/docs/5.1/validation#rule-array for the array validation rule.

$this->validate($request, [
    'email' => 'required|array.email'
]);

Note: I'm using laravel 5.1 version

Update - as per request.

enter image description here

2 Answers 2

2

checked is validate:

above 5.2

$this->validate($request, [
    'email.*' => 'required|array|email'
],[
    'email.required' => 'message required',
    'email.array' => 'message array',
    'email.email' => 'message email',
]);

OR

Less than 5.2

    $validator = \Validator::make($request->all(), [
        'email' => 'array',

        /* Other rules */

    ],[
        'email.required' => 'message required',
        'email.array' => 'message array',
        'email.email' => 'message email',
    ]);

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

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


    dd('Success All Email ;)');
6
1

You need custom validator. In Laravel Request you can do something like that

public function __construct() {
    Validator::extend("emails", function($attribute, $value, $parameters) {
        $rules = [
            'email' => 'required|email',
        ];
        foreach ($value as $email) {
            $data = [
                'email' => $email
            ];
            $validator = Validator::make($data, $rules);
            if ($validator->fails()) {
                return false;
            }
        }
        return true;
    });
}

public function rules() {
    return [
        'email' => 'required|emails'
    ];
}

Or

Validating Arrays laravel 5.2 onwards :

Validating array form input fields doesn't have to be a pain. For example, to validate that each e-mail in a given array input field is unique, you may do the following:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

Likewise, you may use the * character when specifying your validation messages in your language files, making it a breeze to use a single validation message for array based fields:

'custom' => [
    'person.*.email' => [
        'unique' => 'Each person must have a unique e-mail address',
    ]
],

Hope this helps you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.