Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Validate email array in Laravel 5.2 wth custom validator
<?php
/**
* This service provider handles a few custom validation rules.
*
* PHP version 5.5.9
* @package Snipe-IT
* @version v3.0
*/
namespace App\Providers;
use Validator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Custom email array validation.
*
* This is used when you are collecting a comma-separated list of email addresses
* (which is obviously a string), but need to validate each email address individually.
* First we break the string out into an array, and then invoke the built-in Laravel
* validation rule for email.
*
* This basically creates a new named validation rule, called email_array. I can
* now use this as I would any other Laravel validation rule. For example, if I were
* handling validation through a Laravel form request, I could do:
*
* public function rules()
* {
* return [
* ...
* "alert_email" => 'email_array',
* ...
* ];
* }
*
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @return void
*/
public function boot()
{
// Email array validator
Validator::extend('email_array', function($attribute, $value, $parameters, $validator) {
$value = str_replace(' ','',$value);
$array = explode(',', $value);
foreach($array as $email) //loop over values
{
$email_to_validate['alert_email'][]=$email;
}
$rules = array('alert_email.*'=>'email');
$messages = array(
'alert_email.*'=>trans('validation.email_array')
);
$validator = Validator::make($email_to_validate,$rules,$messages);
if ($validator->passes()) {
return true;
} else {
return false;
}
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
@cristianmeza

This comment has been minimized.

Copy link

@cristianmeza cristianmeza commented Aug 17, 2018

Thanks for sharing this

@kyleahughes

This comment has been minimized.

Copy link

@kyleahughes kyleahughes commented Aug 13, 2019

This took me about two weeks to figure out. Thank you!

@franciscoarnaldog

This comment has been minimized.

Copy link

@franciscoarnaldog franciscoarnaldog commented Aug 26, 2019

there is a typo in:
$value = str_replace(' ','',$value);
just add a comma:
$value = str_replace(' ',',',$value);

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