views:

332

answers:

1

I need to run the built-in validations on the login field prior to actually creating the user record, is there a way to do this in Authlogic? The reason for is when a user types in a new login, AJAX is invoked to check and see that the login in unique, valid, etc. Once that is done, the user can enter his email to claim the login, it's a 2 step process.

+1  A: 

The User model uses ActiveRecord validations, so this isn't specific to Authlogic. If you want to run the validations on a model you can call user.valid?. This will return true or false depending on if the entire model is valid. However it also fills up the user.errors object so you can then check if a given attribute is valid.

Here is some code that uses RJS to do the AJAX. But you can use anything and organize it however you want.

user = User.new(params[:user])
user.valid? # we aren't interested in the output of this.
error = user.errors.on(:login)
if error
  page.insert_html :before, "user_login", content_tag(:span, error, :class => "error_message")
end

You may be interested in my Mastering Rails Forms screencast series where I cover this topic in the 2nd episode.

ryanb
Thanks Ryan, I subsequently learned that Authlogic leverages ActiveRecord validations and ended up using the validate_attributes plugin. Your suggestion is a great alternative, thanks for sharing.
Bob