back to list

Easy form validation with UJS and Rails 3

  January 03, 2011 — written by Chris Sloan | 1 comment »

In a previous post, Rails 3, jQuery & UJS, I talked about how easy Rails has made it to do remote forms or even linking to remote actions. It covered how to set up the basics of a remote form to gather the information and let the user know something is being processed. The only question I didn’t cover is, what happens when a form returns a validation error? It’s as easy as making a generic js.erb file.

The setup

Assuming that you already have your UJS working to save the data when everything validates, let’s setup a way to handle when the data does not validate. I will just be covering the example of creation, but this can easily be applied to the update action as well.

The controller

def create
    @bar =[:foo])
    respond_to do |format|
            format.html { } #index.html
            format.js  { } #create.js.erb
            format.html { } #new.html
            format.js  {
            render :template=>"shared/ujs/form_errors.js.erb", 
            :item => @bar, 
            :notice => 'There were errors creating your bar.’

The important part of this is the handling of when it doesn’t save from a JavaScript call, it renders a js.erb file called form_errors.js.erb and passes appropriate hash. I have also created another local variable called notice that is used as a temporary flash.

The form_errors.js.erb file

Since rails form helpers handle creation of forms the same way no matter what the object is, to reduce code duplication, using the same error handling file goes a long way.

The following is what I typically put into my form error handling js.erb file:

// to hold the form element IDs
var errorIDs = new Array();

// to hold the error messages
var errorMessages = new Array();

Since Rails holds the messages and object ID’s in separate methods on the object it returns, it is easiest to store these in two separate arrays to call together later using their index.

The next part is crucial to finding and storing the DOM elements on the page that have validation errors. Using the way Rails form helpers place ID’s on the fields (type_object), you can store the exact DOM object into the array. This is of course if you haven’t broken Rails convention in naming your objects.

// Loop through all the error objects to story as JS objects
<% item.errors.each do |error_object| %>
    <% if params[:from_modal] %>
    errorIDs.push("#<%= item.type.downcase %>_<%= error_object %>");
    <% else %>
    errorIDs.push("#<%= item.type.downcase %>_<%= error_object %>");
    <% end %>
<% end %>

Next you want to loop through all the error messages and store them in the array.

// Loop through all the error messages to store for use
<% item.errors.full_messages.each do |msg| %>
    errorMessages.push("<%= msg %>");
<% end %>

Now to handle these freshly created arrays and display the errors:

// Attach the messages to the error form objects and show some visibles
$.each(errorIDs, function(index, value){
    $(errorIDs[index]).attr(“title”, errorMessages[index]).addClass(“error_field”);

This is a quick example of how to handle the form errors by giving the DOM element a title and adding a class to signify that it’s an error field. I like to use a jQuery plugin called QTip which you can place on the form fields. When the field is then selected, a tooltip pops up with the error message.

Other than that, styling up the form errors is all you have to do. Of course, there are many ways to validate a form before it is even sent to the server, but this is a great fall back method until you have that in place.

filed in: Geekery, Usability Interface | permalink

1 shared their opinion. ADD YOURS »

Paul Hepworth said on 01/04 @ 04:35 AM
I didn't realize that rails doesn't have this included in any of the guides or documentation. Maybe you should add it? Good work, Sloan!

Add your opinion here

Commenting is not available in this weblog entry.
March 2017
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31  
top of page

where you can find me

RailsConf 2010

Flickr Github Working with Rails Linked In

my twitter tweets

follow me