Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vmosoti/8ef268588cbdbf33f263e4733571254b to your computer and use it in GitHub Desktop.
Save vmosoti/8ef268588cbdbf33f263e4733571254b 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.
@OmdaMukhtar
Copy link

OmdaMukhtar commented Oct 24, 2018

this code useless !!!
you should put example for beginner

@sloan58
Copy link

sloan58 commented Nov 18, 2019

I disagree with the comment above. This code is definitely not useless. While a more detailed example might be better for beginners, I found this example very helpful to get a head start on how to validate my comma separated field. Thanks for posting.

@kartikkapatel
Copy link

kartikkapatel commented Feb 6, 2020

<?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],
]);

@awwal1999
Copy link

@kartikkapatel Thanks for the solution!

@redbonzai
Copy link

All Examples here, are very well done.
The adjectives I would use here would be: Insightful, creative, and concise.
Absolutely nothing here is even remotely useless.
Keep up the great work!

@stobys
Copy link

stobys commented Oct 12, 2021

Perfect, just what I needed. Thx mate.

@G3z
Copy link

G3z commented Feb 15, 2022

@kartikkapatel solutions fails for nested attributes and there is no need to use "{$attribute}"

<?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'
            ]
        )->passes();
    }

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

now this works

use App\Rules\Emails\CommaSeparatedEmails;

$request->validate([
      'some.nested.field' => ['nullable', new CommaSeparatedEmails],
]);

@justsanjit
Copy link

justsanjit commented Feb 19, 2023

Nice snippet. I found a spatie's package which does something similar https://github.com/spatie/laravel-validation-rules#delimited

@BmpCorp
Copy link

BmpCorp commented Dec 15, 2023

"attribute" => explode(',', $value)

can be further transformed to

"attribute" => array_map('trim', explode(',', $value))

if you want comma and space separated emails (which is more natural for some users) to be valid too.

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