Ruby on Rails/ActiveRecord/Validations



ActiveRecord supports a variety of model validation methods and allows for addition new methods as needed.

General Usage


For a complete reference of all validations check out the official guide or the API documentation

Additionally you can apply a validation to one or more attributes using the validate_each directive:

  class Person < ActiveRecord::Base
    validates_each :first_name, :last_name do |record, attr, value|
      record.errors.add attr, 'starts with z.' if value[0] == ?z

It is also possible to define validations via custom methods or blocks:

  • validate
  • validate_on_create
  • validate_on_update

For example:

    class Person < ActiveRecord::Base
      validate :validate_email

      def validate_email
        record.errors.add :email, 'Invalid email' unless email =~ /@/

Normally validation occurs whenever a record is created or saved, however you can force validation to *not* occur using the save_with_validation method passing @false@ as the argument.

Important Validators



validates_acceptance_of :play_rules

If you need to check if the user has set or "accepted" a certain checkbox you can use this validation. In this case, the check box with the HTML attribute "name='play_rules'" needs to be checked in order to pass validation.



This validator checks if an input field has been entered correct both times. For example if you want the user to enter his password 2 times to make sure he enters the correct password (this is seen very often when registering for a site) this is the helper you want to use. To use it, make sure to define it correctly in your view (Note the _confirmation):

<%= text_field :user, :password%>
<%= text_field :user, :password_confirmation %>



validates_format_of accepts a regular expression and checks for the input with the provided pattern given by the :with clause. Also note, that we used a customized message with this helper. This can be done with every validator in the same manner.

validates_format_of :username, :with => /\A[a-zA-Z]+\z/,  :message => "Please use only regular letters as username"


validates_length_of :username, :minimum => 5, :maximum => 50
validates_size_of :address, :in => 5..100

The length_of/size_of validator comes in handy if you need to check the input for a certain length of characters. In the example above, the username should not be longer than 50 characters and not shorter than 5. Alternatively you can specify a range that should be true in order to validate. Above the address should constist of 5 to 100 characters. Note that length_of and size_of/ are the same.


validates_numericality_of :amount_available

Checks if the input is a number of any kind. To make sure, that the input is only an integer, you may use the optional :only_integer => true command. There are some useful options with this command for example :greater_than => 100 makes sure that the given number will be greater then 100: so 101 will be the first valid number.


validates_presence_of :name

One of the most basic validators, this one checks if anything has been inserted in the given form element ("name" in this case).


validates_uniqueness_of :username

Finally, a bit of a more advanced validator: this one checks inside the database if the attribute is already taken or not. In this case, if the user chooses the username "Paul" and the name "Paul" already exists inside the username column of your database, it won't validate.

with scope


It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example, making sure that a teacher can only be on the schedule once per semester for a particular class.

validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]

When the record is created a check is performed to make sure that no record exists in the database with the given value for the specified attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.

Configuration Options

  • message - Specifies a custom error message (default is: "has already been taken")
  • scope - One or more columns by which to limit the scope of the uniqueness constraint.
  • if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.

When writing your validation keep in mind that you can mix all of these together and there are even more advanced functions you might want to check out.