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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)