Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Forms, Validation and Callbacks

Active Record Validations

Validate Rails models with presence, length, format, numericality, uniqueness, inclusion and confirmation, write custom validators, read errors and show them in forms. Includes runnable stand-ins.

Data from forms, APIs and imports cannot be trusted. A blog post with no title, an email without an @, two users with the same username: all of these should be refused before they reach your database. Validations are rules declared on a model that Rails checks before it saves. If any rule fails, nothing is written, and the model gets a list of errors that you can show to the user.

This lesson covers the built-in validators, conditions, custom validations, the errors object, and why validations are not enough on their own. Real Rails code is read-only; the runnable examples are Ruby stand-ins that behave the same way.

The basics

Ruby
class User < ApplicationRecord
  validates :name,  presence: true, length: { maximum: 80 }
  validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }, uniqueness: { case_sensitive: false }
  validates :age,   numericality: { only_integer: true, greater_than_or_equal_to: 13 }, allow_nil: true
  validates :role,  inclusion: { in: %w[member editor admin] }
  validates :terms, acceptance: true
  validates :password, confirmation: true, length: { minimum: 12 }, if: :password_required?
end

When does Rails run them? On save, create and update, and when you call valid?. Methods ending in ! (save!, create!) raise ActiveRecord::RecordInvalid instead of returning false.

Ruby
user = User.new(name: "")
user.valid?             # => false
user.errors.full_messages
# => ["Name can't be blank", "Email can't be blank", ...]
user.save               # => false, no INSERT happened

Common validators

Validator Checks
presence not nil, not blank (an empty string or only whitespace fails)
absence must be blank
length minimum, maximum, is, in: 3..20
format matches a regular expression (with:)
numericality is a number; options only_integer, greater_than, less_than_or_equal_to, odd
inclusion / exclusion value is (not) in a list or range
uniqueness no other row has this value, with scope: and case_sensitive:
confirmation password equals the virtual password_confirmation
acceptance a checkbox was ticked (a virtual attribute)
comparison compares with another attribute: greater_than: :start_date

Useful options on every validator: message: (custom text), allow_nil:, allow_blank:, on: :create or on: :update, and if: / unless: for conditions.

Ruby
validates :phone, presence: true, if: -> { contact_method == "sms" }
validates :slug, uniqueness: { scope: :blog_id }, on: :create

Presence for associations and booleans

Validate that a parent exists with the association name: validates :author, presence: true (and belongs_to already requires it by default). For a boolean column, presence: true fails on false, so write inclusion: { in: [true, false] }.

Ruby Stand-in: validations and an errors object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Custom validations

When no built-in validator fits, write a method and register it with validate:

Ruby
class Booking < ApplicationRecord
  validate :ends_after_start
  validate :room_is_free, on: :create

  private

  def ends_after_start
    return if starts_at.blank? || ends_at.blank?
    errors.add(:ends_at, "must be after the start") if ends_at <= starts_at
  end

  def room_is_free
    if Booking.where(room_id: room_id).where("starts_at < ? AND ends_at > ?", ends_at, starts_at).exists?
      errors.add(:base, "That room is already booked")
    end
  end
end
Ruby Stand-in: a custom validation method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

errors.add(:base, ...) attaches a message to the whole record. For rules reused across models, extract a class that inherits ActiveModel::EachValidator and use it as validates :url, safe_url: true.

Showing errors in the form

ERB
<%= form_with model: @user do |form| %>
  <% if @user.errors.any? %>
    <ul class="errors">
      <% @user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
    </ul>
  <% end %>
  <%= form.text_field :name %>
  <%= @user.errors[:name].first %>    <%# message for one field %>
<% end %>

Messages come from the I18n files, so you can translate or reword them in config/locales/en.yml. Rails also adds the CSS class field_with_errors around invalid fields when you use the helpers.

Why validations are not enough

Validations run in Ruby, in one process. They can be skipped (update_column, update_all, save(validate: false), raw SQL), and two requests can race. The classic example is uniqueness: two users submit the same email at the same instant, both pass the SELECT check, and both insert. The only real guarantee is a database constraint:

Ruby
add_index :users, "lower(email)", unique: true      # PostgreSQL expression index
add_column :users, :name, :string, null: false
add_check_constraint :users, "age >= 13", name: "age_check"

Use both: validations for friendly messages, constraints for truth. If the unique index fires anyway, rescue ActiveRecord::RecordNotUnique and show the same message.

The same applies to exists?-then-create code ("check then act"). Prefer create_or_find_by or a unique index plus rescue.

Keep validations about the model's own data. Rules about a workflow ("only an admin can publish") belong in authorization code, and rules that need other systems (sending a code by SMS) belong in services or form objects.

Validation contexts

Use on: to apply a rule only in one situation, or define your own context:

Ruby
validates :password, presence: true, on: :create
validates :name, presence: true, on: :profile_update
user.save(context: :profile_update)
user.valid?(:profile_update)

For a multi-step wizard or screen with different rules, a custom context or a form object keeps the model tidy.

Testing validations

Ruby
test "requires a name" do
  user = User.new(email: "[email protected]")
  assert_not user.valid?
  assert_includes user.errors[:name], "can't be blank"
end

Test one rule per test, and use fixtures or small factories to build the rest of the record, as in testing with Minitest.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does save return when validation fails?

    save returns false and skips the INSERT/UPDATE. save! raises ActiveRecord::RecordInvalid instead.
  2. 2. Which validation is right for a boolean column that may be false?

    presence treats false as blank, so it would reject a valid false value.
  3. 3. Why is a uniqueness validation alone not safe?

    The check and the insert are separate steps, so a race is possible. Only a database constraint is airtight.
  4. 4. How do you attach an error to the whole record rather than one attribute?

    The :base key is for messages that are not about a single attribute.

Summary

  • Validations run on save, create, update and valid?; they fill errors and block the write.
  • Built-ins cover presence, length, format, numericality, inclusion, uniqueness, confirmation and more.
  • Use if:, unless:, on: and allow_nil: to adjust when rules apply.
  • Write validate :method for custom rules and errors.add for messages.
  • Pair validations with database constraints; they can be bypassed and races happen.

Next: Callbacks and form objects