



vu[tab]- this will expand to:
vl[tab]this will expand to:
class User < ActiveRecord::Base
validates_uniqueness_of :username
validates_length_of :username, :within => 5..10
end


In addition to the server side validation that's being performed, we're going to add some client side validation using Ajax. We'll do this by displaying a message to the right of the field on the validity of what's been entered. Since we're validating against the database, we will need to make an XMLHTTPRequest back to the server. We can use Rails' observe_field [5] helper method for this task.
<%= f.text_field :username %><span id="message"></span>
<%= observe_field :user_username, # The field to observe
:with => "username", # The input to validate
:frequency => 0.25, # The frequency in seconds to watch for changes
:url => {:action => :validate }, # The action to call when changes occur
:update => :message # The DOM ID to update
%>
def validate
color = 'red'
username = params[:username]
if username.length < 5
message = 'Too short'
elsif username.length > 10
message = 'Too long'
else
user = User.find_all_by_username(username)
if user.size > 0
message = 'Taken'
else
message = 'Available'
color = 'green'
end
end
@message = "<b style='color:#{color}'>#{message}</b>"
render :partial=>'message'
end
<%= @message %>
<%= javascript_include_tag 'prototype' %>All Rails applications come with the prototype [6] and scriptaculous [7] libraries ready to use, but you do need to tell the application that you want to use them.




Firebug [8] is your friend for troubleshooting Rails applications. With Firebug enabled, you can see the requests as you type:
Forgetting to include the Prototype libraries:

Misspelling the field to observe:

Links:
[1] http://demo.script.aculo.us/ajax/autocompleter
[2] http://dev.mysql.com/downloads/mysql/5.0.html#downloads
[3] http://download.netbeans.org/netbeans/6.1/rc/
[4] http://localhost:3000/users
[5] http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html#M000966
[6] http://www.prototypejs.org/
[7] http://script.aculo.us/
[8] https://addons.mozilla.org/en-US/firefox/addon/1843
[9] http://weblogs.java.net/blog/bleonard/archive/2008/04/rails_auto_validate/autovalidation.zip