Search code examples
ruby-on-railsruby-on-rails-4devise

Customize the validation when user sign in in devise


I have a website that uses Devise for authentication.

While sign in if email and password both are empty it is giving me error

Invalid email or password.

but I want to show different error messages for users for different cases:

For instance, if email field is empty and the password is present then show

Email can't be blank.

else if password field is empty and email is present than show

Password can't be blank.

else password and email are unauthenticated than show

invalid email or password

which currently working.

I don't want to remove :validatable from my model.

I tired validates :email, :presence => true, :email => true

from here

but when I sign up it shows 2 errors of

Email can't be blank.

one error of Devise and the other for the model.

please tell me how to do this validation only for user sign-in.


Solution

  • Try this in your devise session controller's create action.

    def create
      user = User.find_by(email: params[:user][:email])
      if user
        if user.valid_password?(params[:user][:password]) 
          sign_in_and_redirect user
        else
          flash[:error] =  "Please enter the valid password."
        end
      end
    end