Validations

How many of us have had the experience of spending hours upon hours creating form validators, whether they are JavaScript or server-side validation. I know I have, and one of the reasons I love Rails: adding validation to your models is as easy as adding one line of code.

Here are the available validators that are useable by the models:

validates_acceptance_of(*attr_names)

Encapsulates the pattern of wanting to validate the acceptance of a Terms of Service checkbox (or similar agreement).

Example:

class Person < ActiveRecord::Base
  validates_acceptance_of :terms_of_service, :message =>
   "must be abided"
end

Options:

message

A custom error message (default is “must be accepted”).

on

Specifies when this validation is active (default is :save; other options are :create and :update).

accept

Specifies the value that is considered accepted. The default value is a string “1”, which makes it easy to relate to an HTML checkbox.

if

Specifies a method, proc, or string to call to determine if the validation should occur. The method, proc, or string should return or evaluate to a true or false value.

validates_associated(*attr_names)

Validates whether the associated object or objects are all valid themselves. Works with any kind of association:

Example:

class Book < ActiveRecord::Base
  has_many :pages
  belongs_to :library

  validates_associated :pages, :library
end

Options:

on

Specifies when this validation is active (default is :save; other options are :create and :update).

if

Specifies a method, proc, or string ...

Get Rails Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.