code16
Published in

code16

Validating critical email address in Laravel

Photo by Luis Quintero on Unsplash
Client error: `POST https://api.mailgun.net/v3/mywebsite.com/messages.mime` resulted in a `400 Bad Request` response:
{"message":"to parameter is not a valid address. please check documentation"}

Space character

request()->validate([
"my_email_field" => [
"required",
"email:rfc,filter",
],
]);
Exemple of an email refused because it contains a space character

DNS Check

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Validator;

class MyCustomEmailRule implements Rule
{
public function passes($attribute, $value)
{
$validator = Validator::make([$attribute => $value], [
$attribute => app()->environment('testing') ? 'email' : 'email:rfc,dns,filter',
]);

return !$validator->fails();
}

public function message()
{
return "The email must be a valid email address.";
}
}
request()->validate([
"my_email_field" => [
"required",
new MyCustomEmailRule(),
],
]);

--

--

About open source projects at CODE 16

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store