Created
January 18, 2012 03:50
-
-
Save longlostnick/1630779 to your computer and use it in GitHub Desktop.
Validates DateTime values in a Rails app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#TIL You can avoid the
.send
with: