Validating with Rails

Written on Tuesday, November 4th, 2008 at 3:38 pm and is filed under Ruby on Rails.

Ruby on Rails is one of the more popular MVC frameworks out there along with .NET, Zend, and CakePHP. Every day more and more resources are being published regarding Ruby on Rails. One of the nice things about Ruby on Rails is that it makes easy to help validate forms within your rails application. If you want to check for the presence of text for a field it would be something like:

validates_presence_of :comment

That checks for the field name comment, like in the code snippet below. This will produce the input tag using rails.

<%= text_field "comment", "comment" %>

The other section to make it all run is the

<%= error_messages_for 'model_name' %>

Place this line of code at the top of your form, and replace “model_name” with the model name your application refers too. It tells the application to look at the validation rules you set up. Once you have those in place, you should not be able to submit the form with a blank input.

A few other predefined rules built in to Ruby on Rails are:

Field should not be empty

Code: validates_presence_of
Example: validates_presence_of :user_name, :password

Field should Numerical

Code: validates_numericality_of
Example: validates_numericality_of :value

Field should not be Unique

Code:validates_uniqueness_of
Example: validates_uniqueness_of :user_name

Field Need to be of size X

Code: validates_length_of
Example: validates_length_of :state_code, :is=>2

Field size Need to be of between X to Y

Code: validates_length_of
Example: validates_uniqueness_of :user_name

To learn more about validation and to read up on the rest of the Rails API, read this

Spread the ♥

  • Digg
  • del.icio.us
  • Facebook
  • NewsVine
  • Mixx
  • Google Bookmarks
  • email
  • Reddit
  • Design Float
  • StumbleUpon
  • Technorati

other related posts...

  1. Cracking down with Ruby on Rails
  2. Installing Ruby on Rails Plugins via MediaTemple
  3. Active Record Already Activated
  4. jQuery Search And Highlight

Take a peak at some more?

One Response to “Validating with Rails”

  1. Please explain in more detail validates_numericality_of
    I just dont understand where this applies

Leave a Reply