views:

881

answers:

2

Is there a way to get Authlogic to validate the format of a password, for instance must contain at least one letter and at least one number? The omission of a validates_format_of_password_options method to be used in the acts_as_authentic config block seems to indicate that Authlogic has the opinion that one should not be imposing such a constraint on one's users.

I thought I would simply put in a normal ActiveRecord validates_format_of :password, but this means that a current_user object I build is inherently invalid, as I can't retrieve the plaintext password (and wouldn't be storing it in that object even if I could!). Upon detecting that my current_user is invalid, Rails or Authlogic (not sure which, since I'm fairly new to both) directs me to my 'edit user' page with a validation error for its password.

A: 

You can use the configuration options given by acts_as_authentic like so:

    # Configuration is easy:
    #
    #   acts_as_authentic do |c|
    #     c.my_configuration_option = my_value
    #   end
    #
    # See the various sub modules for the configuration they provide.

If you go to the modules in the gem you can see additional options they provide. For example if I want to change the default options of the password's length validation:

acts_as_authentic do |c|
 c.merge_validates_length_of_password_field_options({:minimum => 3})
end

You can look inside the acts_as_authentic folder in your "(gems || plugins)/authlogic/acts_as_authentic/" directory for more options. Cheers!

westoque
I do already have `merge_validates_length_of_password_field_options` in my config block and that works as expected. My problem is that no similar method exists for the format of the password field as there do for the login and email fields.
hynkle
You can always monkeypatch it. :-)
westoque
Just patched it—pretty short! Works perfectly.
hynkle
+4  A: 

requires no monkey-patching, but not tied to any future Authlogic changes. Just add this to your User model:

validates_format_of :password, :with => /^(?=.\d)(?=.([a-z]|[A-Z]))([\x20-\x7E]){6,40}$/, :if => :require_password?, :message => "must include one number, one letter and be between 6 and 40 characters"

Of course you can alter the regex to suite your needs.

bassnode
worked perfectly for me!
dalyons
actually, i had to change it slightly to:`/^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){6,}$/`
dalyons