How to validate multiple email in laravel validation?
Asked Answered
G

6

11

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,

Gorizia answered 5/4, 2015 at 6:35 Comment(0)
R
23

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'
    ];
}
Roshelle answered 5/4, 2015 at 8:35 Comment(3)
To extend this answer, remember to add the custom validation message on your validation.php language file.Gonick
Also, the docs suggest putting this in \App\Providers\AppServiceProvider::bootCustomhouse
As of Laravel 5.6 you don't need to do this. See my answer: https://mcmap.net/q/955189/-how-to-validate-multiple-email-in-laravel-validationCloverleaf
C
13

In 5.6 or above you can define your validator rule as follows:

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

This will expect the email key to be an array of valid email addresses.

Cloverleaf answered 12/11, 2018 at 22:37 Comment(0)
E
11

We can achieve this without custom validation,We can overridden a method prepareForValidation

protected function prepareForValidation() 
{
   //Here email we are reciving as comma seperated so we make it array
   $this->merge(['email' => explode(',', rtrim($this->email, ','))]);
}

Then above function will call automatically and convert email-ids to array, after that use array validation rule

public function rules()
 {
     return [
        'email.*' => 'required|email'
     ];
 }
Electrify answered 19/11, 2019 at 6:46 Comment(3)
I like this solution, but I had to wrap the explode call in array_filter to avoid passing a single-value array with an empty string. Also, this is giving me some trouble with displaying validation messages, since it's now failing on e.g. foobar.0 instead of just foobar.Freeloader
You can use public function messages() for format messages like 'foobar.*.required' => 'email format is wrong'. Then foobar.0 will not comeElectrify
This is better and more "Laravel-like". $this->merge(['email' => array_map('trim', explode(',', $this->email))]);Pretonic
J
2

Laravel 5.2 introduced array validation and you can easily validate array of emails :)

All you need is exploding the string to array.

https://laravel.com/docs/5.2/validation#validating-arrays

Judaic answered 28/2, 2016 at 9:44 Comment(1)
Only relevant if there are multiple inputs.Zinnia
P
2

I did it like this. Working good for me. if email or emails ([email protected], [email protected], [email protected]) are coming from a Form like this following custom validator works. This need to be added to - AppServiceProvider.php - file. And new rule is - 'emails'.

    /**
     * emails
     * Note: this validates multiple emails in coma separated string.
     */
    Validator::extend('emails', function ($attribute, $value, $parameters, $validator) {
        $emails = explode(",", $value);
        foreach ($emails as $k => $v) {
            if (isset($v) && $v !== "") {
                $temp_email = trim($v);
                if (!filter_var($temp_email, FILTER_VALIDATE_EMAIL)) {
                    return false;
                }
            }
        }
        return true;
    }, 'Error message - email is not in right format');

And in your controller, it can be used like this:

    $this->validate($request, [
        'email_txt_area' => 'emails',
    ]);
Pestiferous answered 29/11, 2018 at 16:31 Comment(0)
H
1

If you don't want to override prepareForValidation just because of one rule here's another approach using closures:

$rules = [
    'name'  => 'required|string|max:255',
    'email' => [
        'required',
        function ($attribute, $value, $fail) {
            $emails = array_map('trim', explode(',', $value));
            $validator = Validator::make(['emails' => $emails], ['emails.*' => 'required|email']);
            if ($validator->fails()) {
                $fail('All email addresses must be valid.');
            }
        },
    ],
];

Tested with Laravel 9.x

Hg answered 1/12, 2022 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.