Forked from technoknol/custom validator in laravel to validate comma separated emails.php
Created
February 23, 2018 12:50
-
-
Save vmosoti/8ef268588cbdbf33f263e4733571254b to your computer and use it in GitHub Desktop.
custom validator in laravel to validate comma separated emails.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a Laravel 11.x compatible version of a similar rule I wrote for my projects.
This rule supports custom delimiters (defaults to support comma, space, newlines), as well as minimum + maximum number of e-mails. It works properly with nested attributes.
I have also provided the Pest Unit tests which are fairly robust.
Hopefully this helps somebody else out.
Here are the Pest Unit tests: