Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Autovalidation with Rails

DZone's Guide to

Autovalidation with Rails

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

I love it when a web application gives me instant feedback on the validity of my entry. For example:



This is especially true when I'm registering a new user account - submitting the page over and over again because the username I've selected is already taken or the password doesn't meet the requirements is always a drag. So I started looked for examples on how to do this in Rails and couldn't really find anything (possibly because I don't actually know what to call it) - I guess it's most similar to autocompletion, so I'm going with autovalidation. And here are the steps I've put together to get it to work...


Setting Things Up

  1. Download and install MySQL.
  2. Download and install NetBeans 6.1 RC1 or later.


Creating the Rails Project

  1. Create a new Ruby on Rails Application named autovalidation. You can select Finish after the first page of the New Ruby on Rails Application dialog:
  2. Right-click the project and select Run Rake Task > db > create:

  3. Right-click the project and select Generate. Generate a scaffold with the Model Name User and the Attribute Pairs username:string:
  4. Right-click the project and select Migrate Database > To Current Version.
  5. Open user.rb and type the following:
    vu[tab]
    - this will expand to:



    type username over the attribute and press enter.
  6. On the next line in user.rb type the following:

    vl[tab]
    this will expand to:



    type username over the attribute and press enter. Type 5..10 over the 3..20 and press enter. The completed code should look as follows:

    class User < ActiveRecord::Base
      validates_uniqueness_of :username
      validates_length_of :username, :within => 5..10
    end
     


Traditional Server Side Validation

  1. Run the project and browse to http://localhost:3000/users. Try to create a new user such as bill:

  2. Okay, create william.
  3. Try to create william again:



    Let's enhance this application with more user friendly "autovalidation"...


Lets Autovalidate

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 helper method for this task.

  1. First we need to create a named placeholder for the message. Open new.html.erb and add a <span> tag after the text field as follows:

    <%= f.text_field :username %><span id="message"></span>
  2. Now we'll use Rails' observe_field method to watch changes to that field. Add the following before the closing <% end %> tag:

        <%= 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
                          %>
  3. Create the validate action. Open users_controller.rb and add the following:

      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

    You'll notice in the last line of the validate action above we're rendering a partial. This partial, which we'll create next, will be dynamically rendered inside the span tag we defined in step 1 above.
  4. Create a new ERB file named _message in Views > users. Replace its contents with the following:
    <%= @message %>
  5. Open users.html.erb and add the following before the closing </head> tag:
    <%= javascript_include_tag 'prototype'  %>
    All Rails applications come with the prototype and scriptaculous libraries ready to use, but you do need to tell the application that you want to use them.


Run with Autovalidate

  1. Switch to the browser and start creating a new user (you'll need to refresh the browser once to load the prototype JavaScript libraries):







Troubleshooting

Firebug is your friend for troubleshooting Rails applications. With Firebug enabled, you can see the requests as you type:


A couple of things that tripped me up

    Forgetting to include the Prototype libraries:

    Misspelling the field to observe:


The Completed Application

autovalidation.zip

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}