.

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.

Form: “please enter a unique login id’
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

  1. 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.
  2. 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.

  1. # view file
  2. <%= text_field_with_auto_complete :user, :login_id %><div id=login_error></div>
  3.  
  4. # controller file
  5.  
  6. def auto_complete_for_user_user_name
  7.   @user = User.find_by_user_name(params[:user][:user_name])
  8.    render :update do |page|
  9.      page.replace_html ‘login_error’, (@user ? "Login id already in use" : "")
  10.    end
  11. 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.

5 Responses to “Using an auto_complete to ensure uniqueness”

  1. Jason
    October 9th, 2006 | 12:58 pm

    Sweet. Bookmarked. Will use this on my sites. =)

  2. October 10th, 2006 | 12:14 am

    Interesting use of text_field_with_auto_complete! *claps*

  3. November 10th, 2006 | 4:22 pm

    Thanks for posting this. Keep the tips flowing.

  4. jean-sébastien
    January 31st, 2007 | 6:59 pm

    really nice.
    how can i manage to do it with passwords?

  5. January 9th, 2010 | 8:45 am

    Interesting use of auto_complete. But I’m surprised you haven’t set any entry in the routes.rb file.

Leave a reply