Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save technoknol/d52eb295608d18b86e25663107663204 to your computer and use it in GitHub Desktop.
Save technoknol/d52eb295608d18b86e25663107663204 to your computer and use it in GitHub Desktop.
custom validator in laravel to validate comma separated emails.
<?php
// custom validator in laravel to validate comma separated emails.
\Validator::extend("emails", function($attribute, $values, $parameters) {
$value = explode(',', $values);
$rules = [
'email' => 'required|email',
];
if ($value) {
foreach ($value as $email) {
$data = [
'email' => $email
];
$validator = \Validator::make($data, $rules);
if ($validator->fails()) {
return false;
}
}
return true;
}
});
// Custom message for that validation
// pass this array as third parameter in \Validator::make
array('emails' => ':attribute must have valid email addresses.');
// Usage:
$rules['notifications'] = 'emails'; // 'emails' is name of new rule.
@kartikkapatel
Copy link

<?php

namespace App\Rules\Emails;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Validator;

class CommaSeparatedEmails implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return !Validator::make(
            [
                "{$attribute}" => explode(',', $value)
            ],
            [
                "{$attribute}.*" => 'required|email'
            ]
        )->fails();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must have valid email addresses.';
    }
}

Usage:

use App\Rules\Emails\CommaSeparatedEmails;

$request->validate([
      'daily_reports' => ['nullable', new CommaSeparatedEmails],
      'weekly_reports' => ['nullable', new CommaSeparatedEmails],
]);

@gigo6000
Copy link

gigo6000 commented Apr 8, 2021

If there's a space after a comma the validation fails, so we should trim the email addresses:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Validator;

class CommaSeparatedEmails implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed  $value
     *
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return ! Validator::make(
            [
                "{$attribute}" => array_map('trim', explode(',', $value)),
            ],
            [
                "{$attribute}.*" => 'email',
            ]
        )->fails();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must have valid email addresses.';
    }
} 

@judgej
Copy link

judgej commented Jun 3, 2021

Very nice - set up a custom validator to first transform the data from a string to an array, then apply a validation rule to every element of the array.

I have to sat it out loud, then it makes it easier to find next time I need this :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment