Rails: Validations of Dates, Numerics and Strings with ComparisonValidator

Posted . Visible to the public.

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

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
Last edit
Julian
License
Source code in this card is licensed under the MIT License.
Posted by Julian to makandra dev (2022-10-14 07:27)