Skip to content

Instantly share code, notes, and snippets.

@Ranjithkumar
Created September 20, 2010 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ranjithkumar/587623 to your computer and use it in GitHub Desktop.
Save Ranjithkumar/587623 to your computer and use it in GitHub Desktop.
"Date/Time validation" - class method
ActiveRecord::Base.class_eval do
def self.validates_date(*attr_names)
# Set the default configuration
new_options = attr_names.extract_options!
if new_options[:compare_time]
configuration = { :after => Time.now.utc}
else
configuration = { :after => Date.today }
end
# Update defaults with any supplied configuration values
configuration.update(new_options)
# Validate each attribute, passing in the configuration
validates_each(attr_names, configuration) do |record, attr_name, value|
unless value.nil?
value = new_options[:compare_time] ? value : Date.parse(value.strftime('%Y/%m/%d'))
if configuration[:after].is_a?(Time) || configuration[:after].is_a?(Date)
after_date = new_options[:compare_time] ? configuration[:after] : Date.parse(configuration[:after].strftime('%Y/%m/%d'))
else
s_date = record.send(configuration[:after])
after_date = new_options[:compare_time] ? s_date : (s_date.present? ? Date.parse(s_date.strftime('%Y/%m/%d')) : s_date)
end
unless after_date.nil?
e_msg = configuration[:after].is_a?(Time) ? configuration[:after].strftime("%B %d, %Y %H:%M%p").to_s : (configuration[:after].is_a?(Date) ? (configuration[:after]-1).strftime("%B %d, %Y").to_s : configuration[:after])
record.errors.add(attr_name, I18n.t('must_be_after') + e_msg.to_s.humanize) if value <= after_date
end
end
end
end
end
@Ranjithkumar
Copy link
Author

This class method has the ability to do date and time validation checking with ActiveRecord.
The validators can be used to parse strings into Date and Time objects as well as range check.

class Project < ActiveRecord::Base
# Validates that start_date is in the future
validates_date :start_date, :o n => :create
# Validates that end_date is later than start_date
validates_date :end_date, :after => :start_date
end

class Slot < ActiveRecord::Base
# Validates that start_date is in the future
validates_date :start_date, :compare_time => true, :o n => :create
# Validates that end_date is later than start_date
validates_date :end_date, :after => :start_date, :compare_time => true
end

Example:-
p=Project.new
p.start_date = Date.today-1
p.end_date = Date.today -2
p.valid? #false
p.errors.full_messages #["Start date must be after September 04, 2010", "End date must be after Start date"]

You can customise the error messages for dates or times using I18n.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment