AnonCPT
AnonCPT

Reputation: 21

How can i validate a list of emails in Laravel 5.4

I have a list of emails that get sent from the client side which are seperated by a comma. How can i validate all these emails to ensure that they are valid emails? e.g a user can capture emails in a text box like this [email protected], [email protected],[email protected] etc

Upvotes: 0

Views: 707

Answers (2)

Ruman
Ruman

Reputation: 191

If you are trying to validate an array of emails then easiest way to validate is to use dot . syntax with a wildcard *. Here's the example:

$request->validate([
    'emails.*' => ['email'],
    ...
]);

Upvotes: -1

Leo Rams
Leo Rams

Reputation: 729

I built a similar functionality at some point by using customer validation functions

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

Upvotes: 1

Related Questions