Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 351
MisterPi Avatar asked Nov 02 '16 12:11

MisterPi


People also ask

How can I check email is valid in laravel?

Laravel provides validation rules to validate input fields. You can check if an email is valid or not in Laravel using the validate method by passing in the validation rules. You can validate your email addresses using one or more of the validation rules we have discussed.

How do you validate exact words in laravel?

To get the exact words to validate you can make use of Rule::in method available with laravel. Using Rule::in method whatever the values provided by this rule has to be matched otherwise it will fail.


3 Answers

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())
{
    ...
}
like image 184
Frnak Avatar answered Oct 20 '22 15:10

Frnak


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;
        });
like image 27
MisterPi Avatar answered Oct 20 '22 15:10

MisterPi


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.');
   }
}],
like image 38
Eugine Joseph Avatar answered Oct 20 '22 15:10

Eugine Joseph