Skip to content

Instantly share code, notes, and snippets.

@gormus
Created January 14, 2018 20:07
Show Gist options
  • Save gormus/c4c0eb4dd38b050c66b9f78b97d5b6cf to your computer and use it in GitHub Desktop.
Save gormus/c4c0eb4dd38b050c66b9f78b97d5b6cf to your computer and use it in GitHub Desktop.
Laravel validation rule to prevent use of email addresses possessing a disposable (blacklisted) domains.
<?php
// Namespace
namespace App\Validators;
// Using directives
use Cache;
use Carbon\Carbon;
// Domain black list validation class
class DomainBlackListValidator
{
/**
* Array of blacklisted domains.
*
**/
private $domains = [];
/**
* Retrieve latest selection of blacklisted domains and cache them.
*
* @param none.
* @return void.
*
**/
public function refresh()
{
// Define parameters for the cache
$key = "domains.blacklisted";
$duration = Carbon::now() -> addMonth();
$url = "https://raw.githubusercontent.com/ivolo/disposable-email-domains/master/index.json";
// Retrieve blacklisted domains (preferably from the cache)
$this -> domains = Cache::remember($key, $duration, function() use($url) {
return json_decode(file_get_contents($url), true);
});
}
/**
* Generate the error message on validation failure.
*
* @param string $message.
* @param string $attribute.
* @param string $rule.
* @param array $parameters.
* @return string.
*
**/
public function message($message, $attribute, $rule, $parameters)
{
// Provide custom error message
return "The $attribute does not allow disposable email (blacklisted) domains.";
}
/**
* Execute the validation routine.
*
* @param string $attribute.
* @param string $value.
* @param array $parameters.
* @return bool.
*
**/
public function validate($attribute, $value, $parameters)
{
// Load blacklisted domains
$this -> refresh();
// Extract domain from supplied email address
$domain = str_after(strtolower($parameters[0]), "@");
// Run validation check
return ! in_array($domain, $this -> domains);
}
}
<?php
// Namespace
namespace App\Providers;
// Using directives
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
// Validation service provider
class ValidationServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @param none.
* @return void.
*
**/
public function boot()
{
// Add custom validation rules
Validator::extend("blacklist", "App\Validators\DomainBlackListValidator@validate");
// Add custom validation messages
Validator::replacer("blacklist", "App\Validators\DomainBlackListValidator@message");
}
/**
* Register any application services.
*
* @param none.
* @return void.
*
**/
public function register()
{
//
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment