mornaner
mornaner

Reputation: 2424

rails password update validation issue

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?

Upvotes: 1

Views: 413

Answers (2)

Bohdan
Bohdan

Reputation: 8408

You might use conditional validations

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

Upvotes: 0

Svilen
Svilen

Reputation: 2648

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.

Upvotes: 1

Related Questions