MisterPi
MisterPi

Reputation: 1671

Email validation rule in Laravel?

I do email validation using the simple rule:

'email' => 'required|email|unique:users,email',

How do I modify the option unique so that it will work only if the entered email is different from the primordial?

A sample:

The field email contains the default value from table users: [email protected]

Then I push the button without making any changes in the form I should not check unique:users.

Otherwise, if I even changed one symbol in [email protected] I must validate the incoming value using: unique:users.

Upvotes: 8

Views: 78064

Answers (3)

Eugine Joseph
Eugine Joseph

Reputation: 1558

I think it is as loophole in laravel validation.
I update the code for email validation. This is working fine for me.

'email' => [
   'required', 'email:rfc',
   function($attribute, $value, $fail) {
   if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
      $fail($attribute . ' is invalid.');
   }
}],

Upvotes: 3

MisterPi
MisterPi

Reputation: 1671

I did this using the conditional checks:

 $validator = Validator::make($request->all(), []);

 $validator->sometimes('email', 'unique:users,email', function ($input) {
            return $input->email !== Auth::user()->email;
        });

Upvotes: 7

Frnak
Frnak

Reputation: 6812

You can find an example here https://laracasts.com/discuss/channels/requests/laravel-5-validation-request-how-to-handle-validation-on-update

You will need to have multiple rules depending on the request method (update or create) and you can pass a third parameter to unique to ensure no fail if you know the user / email

'user.email' => 'required|email|unique:users,email,'.$user->id,

Switch for method

switch($this->method())
{
    ...
}

Upvotes: 10

Related Questions