1

I have the following validation:

validates :password, :presence => true, :confirmation => true, :length => { :within => 6..40 }, :format => { :with => pass_regex }, :unless => :nopass?

Then, when I try to update without password (nopass? is true) the following errors appear:

There were problems with the following fields:

Password is too short (minimum is 6 characters)
Password is invalid

Notice that the :unless works on :presence and :confirmation but not in :lenght or :format.

How could I fix this?

1
  • which Rails version do you use? Commented Oct 3, 2011 at 9:59

2 Answers 2

1

I've had some strange issues with the :confirmation flag as well, which I never figured out, but that's how I solved the problem in my Rails 3.0.x app:

attr_accessor :password_confirmation

validates :password, :presence => true, :length => {:within => PASSWORD_MIN_LENGTH..PASSWORD_MAX_LENGTH}

validate :password_is_confirmed

  def password_is_confirmed
 if password_changed? # don't trigger that validation every time we save/update attributes
  errors.add(:password_confirmation, "can't be blank") if password_confirmation.blank?
  errors.add(:password_confirmation, "doesn't match first password") if password != password_confirmation
 end
end

I realise this is not an explanation why your code isn't working, but if you're looking for a quick temporary fix - I hope this will help.

Sign up to request clarification or add additional context in comments.

2 Comments

How do you define password_changed? I encrypt the password before saving.
For all attributes you automatically get a _changed? method, that's coming from ActiveRecord. You can actually try using it like that: validates_presence_of :password_confirmation, :if => :password_changed? Haven't tried that myself, but you might be able to fit it in your code above. (note: you still need the attr_accessor :password_confirmation in this case; I think :confirmation => true is supposed to do exactly that)
0

You might use conditional validations

class Person < ActiveRecord::Base
  validates :surname, :presence => true, :if => "name.nil?"
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.