0
0
Ruby on Railsframework~5 mins

Custom validation methods in Ruby on Rails

Choose your learning style9 modes available
Introduction

Custom validation methods let you check if your data is correct in ways built-in checks can't. They help keep your app's information clean and reliable.

When you need to check a rule that Rails does not provide by default.
When validating a combination of fields together.
When you want to add a special error message for a unique condition.
When you want to reuse a validation logic inside your model.
When you want to keep your validation code organized and clear.
Syntax
Ruby on Rails
class ModelName < ApplicationRecord
  validate :custom_validation_method

  def custom_validation_method
    if some_condition_is_not_met
      errors.add(:attribute_name, "custom error message")
    end
  end
end

The method name after validate is your custom check.

Use errors.add to add an error message to a specific attribute.

Examples
This checks if the user's age is less than 18 and adds an error if so.
Ruby on Rails
class User < ApplicationRecord
  validate :must_be_adult

  def must_be_adult
    if age.present? && age.to_i < 18
      errors.add(:age, "must be at least 18 years old")
    end
  end
end
This ensures the product price is a positive number.
Ruby on Rails
class Product < ApplicationRecord
  validate :price_must_be_positive

  def price_must_be_positive
    errors.add(:price, "must be greater than zero") if price.to_f <= 0
  end
end
This validates that the start date is earlier than the end date.
Ruby on Rails
class Booking < ApplicationRecord
  validate :start_date_before_end_date

  def start_date_before_end_date
    if start_date.present? && end_date.present? && start_date > end_date
      errors.add(:start_date, "must be before end date")
    end
  end
end
Sample Program

This Event model checks that the name is not empty and starts with a capital letter. The example creates an event with a lowercase name and shows the validation errors.

Ruby on Rails
class Event < ApplicationRecord
  validate :name_cannot_be_blank_and_must_start_with_capital

  def name_cannot_be_blank_and_must_start_with_capital
    if name.blank?
      errors.add(:name, "can't be blank")
    elsif name[0] != name[0].upcase
      errors.add(:name, "must start with a capital letter")
    end
  end
end

# Example usage:
event = Event.new(name: "party")
valid = event.valid?
errors = event.errors.full_messages

puts "Is event valid? #{valid}"
puts "Errors: #{errors.join(', ')}"
OutputSuccess
Important Notes

Custom validations run when you call valid? or try to save the record.

Always add errors to the errors object to stop saving invalid data.

You can add errors to specific attributes or to the base object for general errors.

Summary

Custom validation methods let you write your own rules for data checks.

Use validate :method_name and define the method to add errors.

This keeps your app's data clean and your validation logic clear.