Rails Validations Every Backend Developer Should Know

Learn the most important Rails validations for backend development, including presence, length, numericality, custom validators, and database constraints.

By Anderson Alvarez Vásquez · 2026-07-05

  • ruby
  • tutorials
  • programming

Rails Validations: A Practical Guide for Backend Developers Rails validations are a key part of building reliable backend applications. They help protect data integrity before records are saved to the database and make business rules explicit inside your models. Why Validations Matter Validations prevent invalid data from entering your application. For example, a user should not be created without an email: ruby class User < ApplicationRecord validates :email, presence: true end If the email is missing, Rails will not save the record: ruby user = User.new user.valid? = false user.errors :email = "can't be blank" Presence Validation presence ensures that a value is not blank. ruby class Post < ApplicationRecord validates :title, presence: true end This is useful for required fields such as names, titles, emails, slugs, and descriptions. ruby Post.create title: nil .valid? = false Uniqueness Validation uniqueness ensures that a value is not already used by another record. ruby class User < ApplicationRecord validates :email, uniqueness: true end For case-insensitive checks: ruby class User < ApplicationRecord validates :email, uniqueness: { case sensitive: false } end However, Rails validation alone is not enough. You should also add a unique database index: ruby add index :users, :email, unique: true Without a database index, two requests can still create duplicate records at the same time. Length Validation length validates the size of a string or collection. ruby class Post < ApplicationRecord validates :title, length: { minimum: 5, maximum: 120 } end You can also use an exact length: ruby class Token < ApplicationRecord validates :code, length: { is: 6 } end Length validations are useful for titles, usernames, passwords, summaries, and codes. Format Validation...