2

I am using Laravel's Validation through FormRequest. An extract of the code is here. It seems laravel's validation is letting email addresses like "user@hotmail" through.

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class DirectorForm extends FormRequest
{
    public function rules()
    {
        return [
            'email' => 'required|email',
        ];
    }
}

it seems the above validation allows "username@hotmail", which isn't a valid email address.

Did i set it up wrongly

Ong Pe Hon
  • 305
  • 3
  • 11

4 Answers4

2

Actually user@hotmail is a valid email, as user@localhost can also be a valid email address.
If you want to check that if the email address also contains a TLD, you can try:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class DirectorForm extends FormRequest
{
    public function rules()
    {
        return [
            'email' => 'required|regex:.+@.+\..+',
        ];
    }
}

For more regex email validation rules take a look at this answer.

frzsombor
  • 2,274
  • 1
  • 22
  • 40
1

Use the regex from: https://emailregex.com/

And combine with Laravel regex rule: https://laravel.com/docs/5.8/validation#rule-regex

loic.lopez
  • 2,013
  • 2
  • 21
  • 42
0

It appears validation is working as expected. Thanks for reading!

Ong Pe Hon
  • 305
  • 3
  • 11
0

You can write custom validation for an email in AppServiceProvider like

Boot method

Validator::extend('email_address', function ($attribute, $value, $parameters, $validator) {
            return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $value)) ? FALSE : TRUE;
        });

Rules

public function rules()
    {
        return [
            'email' => 'required|email_address',
        ];
    }
bhavinjr
  • 1,663
  • 13
  • 19