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.
@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