views:

142

answers:

4

I have a User model, which has an email and a password field. For security, these may not be equal to each other. How can I define this in my model?

+4  A: 

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
John Feminella
Thanks John!!!!
Time Machine
+1  A: 

all you need is to create validation rule in your model for example

class User < ActiveRecord::Base
  def validate_on_create
    if email == password
      errors.add('password', 'email and password can't be the same')
    end
  end
end
sys
I don't think this is right. We want `validate`, not `validate_on_create`, because we need to check on all saves that the e-mail isn't the password (not just at creation time).
John Feminella
There is a syntax error (typo) in error message: You cannot use single quote marks in string which is single quoted ;-)
Dejw
+3  A: 

It depends how Your password is stored:

class User < ActiveRecord::Base
    validate :email_and_password_validation

    def email_and_password_validation
        if self.email == self.password
            errors.add_to_base("Password must be different from email") 
        end
    end
end

This would work if Your password is stored literally, but You can perform the same thing with email (e.g. create a hashed version) and check for equality with password. E.g:

class User < ActiveRecord::Base
    validate :email_and_password_validation

    def email_and_password_validation
        if make_hash(self.email) == self.hashed_password
            errors.add_to_base("Password must be different from email") 
        end
    end
end

My example is taken from http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M002162

Your situation is quite general so You can be interested in creating custom validation method. Everything is covered here: http://guides.rubyonrails.org/active_record_validations_callbacks.html#creating-custom-validation-methods

Dejw
+3  A: 

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.

klew