How to validate multiple email in laravel validation?

Subhod30 picture Subhod30 · Apr 5, 2015 · Viewed 15.4k times · Source

I have done all the things for the validation for the variable in laravel but for emails I got one simple problem.

From doc of Laravel,

'email' => 'required|email'

I got to know this is for only one email address but for like,

[email protected],[email protected], def@ghi,com

When I send array of the email i still get email is not a valid email. I have done more like,

'email' => 'required|email|array'

But I still got error. can any body help.

Thanks,

Answer

Margus Pala picture Margus Pala · Apr 5, 2015

You need to write custom Validator, which will take the array and validate each ofthe emails in array manually. In Laravel 5 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'
    ];
}