How do I validate that two values do not equal each other in a Rails model?

Create custom validataion:

validate :check_email_and_password

def check_email_and_password
  errors.add(:password, "can't be the same as email") if email == password
end

But keep in mind that storing password as a plain text is bad idea. You should store it hashed. Try some authentication plugin like authlogic or Restful authentication.


You can use a custom validation method to check this.

class User < ActiveRecord::Base
  # ...

  def validate
    if (self.email == self.password)
      errors.add(:password, "password cannot equal email")
      errors.add(:email, "email cannot equal password")
    end
  end
end

New way:

validates :password, exclusion: { in: lambda{ |user| [user.email] } }

or:

validates :password, exclusion: { in: ->(user) { [user.email] } }