Bulletproof Your Data: The Ultimate Guide to Validations in Ruby on Rails

Raghavendra S
3 min readDec 28, 2024

Validations in Ruby on Rails ensure that your application’s data is clean and consistent. Beyond the built-in validations, sometimes you need to extend functionality using custom methods or third-party gems. This guide covers all possible validation scenarios — from simple presence checks to advanced validations using gems — so you can copy and paste them directly into your Rails project.

Photo by Maksym Mazur on Unsplash

Basic Validations

  1. Presence Validation

Ensure a field is not empty or nil.

class User < ApplicationRecord
validates :name, presence: true
end

2. Length Validation

Restrict the length of a string.

class Post < ApplicationRecord
validates :title, length: { minimum: 5, maximum: 100 }
end

3. Uniqueness Validation

Ensure a field’s value is unique across the database.

class User < ApplicationRecord
validates :email, uniqueness: true

end

Add a Database Index for Safety:

add_index :users, :email, unique: true

4. Format Validation

Check that a field matches a specific format using regex.

class User < ApplicationRecord
validates :email, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }
end

5. Numericality Validation

Ensure a field contains a number.

class Product < ApplicationRecord
validates :price, numericality: { greater_than: 0 }
end

6. Inclusion Validation

Ensure a value is within a specific list.

class User < ApplicationRecord
validates :role, inclusion: { in: %w[admin user guest] }
end

7. Exclusion Validation

Ensure a value is NOT within a specific list.

class User < ApplicationRecord
validates :username, exclusion: { in: %w[admin superuser] }
end

8. Confirmation Validation

Ensure two fields match, such as passwords.

class User < ApplicationRecord
validates :password, confirmation: true
end

9. Acceptance Validation

Use this for terms and conditions checkboxes.

class User < ApplicationRecord
validates :terms_of_service, acceptance: true
end

Advanced Custom Validations

10. Custom Validation Method

Write your own validation logic.

class User < ApplicationRecord
validate :age_must_be_above_18

def age_must_be_above_18
errors.add(:age, “must be greater than 18") if age.present? && age <= 18
end
end

Third-Party Gems for Validations

11. Email Validation: validates_email_format_of

Add robust email validation with the

gem validates_email_format_of

Gem Installation:

gem install validates_email_format_of

Usage:

class User < ApplicationRecord
validates_email_format_of :email
end

12. Phone Number Validation: phonelib

Add phone number validation using the phonelib gem.

Gem Installation:

gem install phonelib

Usage:

class User < ApplicationRecord
validates :phone, phone: true
end

13. Credit Card Validation: active_merchant

Validate credit card numbers using the active_merchant gem.

Gem Installation:

gem install activemerchant

Usage:

require ‘active_merchant’

class Payment < ApplicationRecord
validate :valid_credit_card

def valid_credit_card
errors.add(:credit_card_number, “is invalid”) unless ActiveMerchant::Billing::CreditCard.valid_number?(credit_card_number)
end
end

14. Strong Password Validation: devise

Add strong password validations with devise.

Gem Installation:

gem install devise

Usage:

class User < ApplicationRecord
validates :password, format: { with: /(?=.*[A-Z])(?=.*[09])(?=.*[!@#$&*])/, message: “must include uppercase, number, and special character” }
end

15. Date Validation: validates_timeliness

Use the validates_timeliness gem for advanced date and time validations.

Gem Installation:

gem install validates_timeliness

Usage:

class Event < ApplicationRecord
validates_date :start_date, on_or_after: :today
end

16. IP Address Validation: ipaddress

Ensure a field contains a valid IP address.

Gem Installation:

gem install ipaddress

Usage:

class Network < ApplicationRecord
validate :valid_ip_address
def valid_ip_address
errors.add(:ip_address, “is invalid”) unless IPAddress.valid?(ip_address)
end
end

Chained Validations Example

Combine multiple validations for a single field.

class User < ApplicationRecord
validates :email, presence: true, uniqueness: true, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }
validates :password, presence: true, length: { minimum: 8 }, confirmation: true
end

Best Practices for Validations

1. Database-Level Enforcement: Use database constraints (e.g., NOT NULL, unique indexes) to complement Rails validations.

2. Error Messages: Customize messages to be user-friendly.

3. Model Cleanliness: Use custom validators or service objects for complex rules.

4. Test Validations: Write tests to ensure your validations work as expected.

Conclusion

Validations in Ruby on Rails provide a flexible and powerful way to maintain data integrity. By combining Rails’ built-in helpers, custom methods, and third-party gems, you can cover all scenarios efficiently. Whether you’re building a small application or a large-scale system, these examples will help you implement validations like a pro.

Let me know in the comments if you have more scenarios to cover or any questions about Rails validations!

Sign up to discover human stories that deepen your understanding of the world.

Raghavendra S
Raghavendra S

Written by Raghavendra S

Artificial enthusiast. Rubyist.

No responses yet

Write a response