#!/usr/bin/env ruby require "active_model" require "active_support/core_ext" # Checks the date is after|before|not after|not before another date. # # validates :next_birthday, date: { after: Time.now, not_after: 1.year.from_now } # # Use the :allow_nil key to skip validation in case the attribute value isn't set. # # validates :next_birthday, date: { after: Time.now, allow_nil: true } # class DateValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) return if value.nil? && options[:allow_nil] value = value.try(:to_date) { after: :>, before: :<, not_after: :<=, not_before: :>= }.each do |key, check| if target = options[key].try(:to_date) record.errors.add attribute, :"#{ key }_date" unless value.try check, target end end end end