October 9, 2006
Using an auto_complete to ensure uniqueness
The Problem
Occasionally there is a need to have a user enter a unique string. For example, if you want to ensure that a new user’s login id is not used by someone else. The traditional rails way of doing this is to set up a ‘validates_uniqueness_of’ validation on the model and then catch the error when you try to save the record.
From the user’s point of view, this can be a horrendously painful experience that can be akin to trying to outsmart the Sphinx.
User: “john smith”
Form: “Wrong, guess again!”
User: “jsmith”
Form: “Nope, getting warmer”
User: “jsmith1″
Form: “You wish! Keep trying!”
User: “as;ldfkjasd;flkajsdf;lakjsd”
Form: “Ha! your id must be only numbers and letters!”
User: “!@!$!@!#!@#!@#!@#%*(#^($!!!!!!!”
Form: “Sorry, wrong again!”
* user navigates to youtube *
The biggest problem here is that there is no feedback to the user if the value they selected is valid until they submit. Some forms will also force you to retype your new password everytime this fails as well. Double ouch!
Solutions
- offer suggestions for valid responses when it fails the first time. Not exactly the best, you might as well autogenerate their id for them and hope they don’t forget it.
- provide feedback with AJAX to let them know if the value is ok.
As you might have guessed from the title of the article, I’m going to show you how to do this with a standard rails auto_complete text field.
-
# view file
-
<%= text_field_with_auto_complete :user, :login_id %><div id=login_error></div>
-
-
# controller file
-
-
def auto_complete_for_user_user_name
-
@user = User.find_by_user_name(params[:user][:user_name])
-
render :update do |page|
-
page.replace_html ‘login_error’, (@user ? "Login id already in use" : "")
-
end
-
end
That’s it. Anytime the auto_complete matches a record, it will change the ‘login_error’ div to indicate there’s a problem.
Net result…. a much better user interface experience and much happier users.
Filed by Kevin Olbrich at 12:33 pm under AJAX, Ruby on Rails, User Interface, auto_complete
6 Comments
Sweet. Bookmarked. Will use this on my sites. =)
Interesting use of text_field_with_auto_complete! *claps*
Thanks for posting this. Keep the tips flowing.
really nice.
how can i manage to do it with passwords?
Interesting use of auto_complete. But I’m surprised you haven’t set any entry in the routes.rb file.
[...] read this article at SciWerks.com and changed the code here and there so that a newbie like me can understand it [...]