Skip to content

Instantly share code, notes, and snippets.

@longlostnick
Created January 18, 2012 03:50
Show Gist options
  • Save longlostnick/1630779 to your computer and use it in GitHub Desktop.
Save longlostnick/1630779 to your computer and use it in GitHub Desktop.
Validates DateTime values in a Rails app
# this sucker takes care of validating datetime fields before rails gets there and
# messes everything up. it should preserve the local time zone from the user input,
# and check for nil. takes date strings of the format m/d/yyyy m:h (am/pm)
# this goes in the model
validates_with DateTimeValidator, :fields => [:add_date]
# this goes in some place like lib/date_time_validator.rb
class DateTimeValidator < ActiveModel::Validator
DATETIME_FORMAT = "%m/%d/%Y %I:%M %P"
def validate(record)
options[:fields].each do |field|
begin
# gotta use the actual string and not the rails fucked time that it 'conveniently' converts to UTC
record[field] = Time.strptime(record.send("#{field}_before_type_cast"), DATETIME_FORMAT)
rescue ArgumentError
record.errors.add(field, "is either invalid or blank")
end
end
end
end
@dgmstuart
Copy link

#TIL You can avoid the .send with:

record.attributes_before_type_cast[field.to_s]

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