by Dan McGrady

Simple Live Validations in Rails

The first day of working with NuLayer, I had the task of adding live validations to a signup form, something very lightweight and clean. Although there are a few plugins (see below), hand coding this into a rails app is really simple.

The Scenario: Validate the username is unique as it’s typed into the forms text field

1) Live_validations controller and validation method

Create a controller to store your validation methods and add the appropriate routes.

2) Message partial

Create a partial that will handle the HTML that is returned for the ajax call.

In your form add an observe_field helper (JRails or Prototype required). This helper will observe the field every 0.5 seconds and pass the value of the text_field via params[:username] to the live_validation controller method.


I used accept.png and cross.png icons from Fam Fam.

Done.

JQuery + Rails Plugin Options

For straight javascript there are a few options, such as jQuery Validation and LiveValidations.com; these are great for basic validations (ex. email has a proper format) but they don’t have access to ActiveRecord.

There is also a rails plugin LiveValidations that hooks up to your existing validations and comes with a form builder for the AJAX, but after testing it: it doesn’t work with nested forms and with hundreds of lines of code it seemed like overkill.

- By Dan McGrady




dMix Redesigned, Contrastream Shutting Down and Joining LearnHub
WeeklyBuilder: A weekly calendar plugin for Rails