Cristian Livadaru's blog

... think again ...

AJAX Validation on Rails

I had a ajax form to add languages in the system in one of my projects. A pretty simple form with just one text field. The problem I had was with validations and display the error message if something goes wrong.
After search the net for a while I came across this blog from bigsmoke which could solve my issues, but after looking a bit it kind of looks a bit complicated and I wanted something more simple.
I took some ideas from bigsmokeand did my own thing.

So here is my implementation of Ajax validation on Rails:

My controller has a “new” action which looks like this

def new
  @language =[:language])
    return if request.xhr?
    render :partial => 'error', :status => 444

The view where the languages are displayed I have added a hidden div which will display the error message if present

Here is where the most stuff happens, in the _error.rjs

page.replace_html 'errors', "Language could not be created. Reason: #{@language.errors.full_messages}"
page.delay(5) do
  page.visual_effect :fade, 'errors'

This replaces the errors div with a message and the errors returned from the validation, it starts a fade with a delay so that the error message will disappear after a while and finally, the div is set to visible.

That’s it! It really is that simple.