Read more

Rails: Validations of Dates, Numerics and Strings with ComparisonValidator

Julian
October 14, 2022Software engineer at makandra GmbH

tl;dr

Since Rails 7+ you can use ComparisonValidator for validations like greater_than, less_than, etc. on dates, numerics or strings.

Example

We have a model for booking a trip. This model has mandatory attributes to enforce dates for the start and the end.

# == Schema Information
#
# start_date :date
# end_date   :date
# ...

class TripBooking < ApplicationRecord
  validates :start_date, presence: true
  validates :end_date, presence: true
end
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

These validations are enough. We also want to ensure, that the end is always after the start date.

class TripBooking < ApplicationRecord
  validates :start_date, presence: true
  validates :end_date, presence: true
  
  validate :end_date_is_after_start_date
  
  private
  
  def end_date_is_after_start_date
    errors.add(:end_date, 'can not be before or equal to the start date') unless end_date.after?(start_date)
  end
end

Since Rails 7+ we can use the ComparisonValidator for these use cases.

class TripBooking < ApplicationRecord
  validates :start_date, presence: true
  validates :end_date, presence: true

  validates :end_date, comparison: { greater_than: :start_date }
  validates_comparison_of :start_date,  greater_than: -> { Date.today }
end

With the ComparisonValidator you can also combine multiple compare options.

class TripBooking < ApplicationRecord
  validates :start_date, presence: true
  validates :end_date, presence: true

  validates_comparison_of :start_date, less_than: :end_date, greater_than: -> { Date.today }
end

Source

Julian
October 14, 2022Software engineer at makandra GmbH
Posted by Julian to makandra dev (2022-10-14 09:27)