Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ActiveModel Validator that checks whether the string value of an attribute is a valid ActiveSupport::TimeZone
class TimeZoneValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless ActiveSupport::TimeZone[value]
record.errors[attribute] << (options[:message] || 'is not a valid time zone!')
end
end
end
# Usage with rails:
#
# Put the validator class into +app/validators/time_zone_validators.rb+ and it will be loaded automatically.
# Create a model with a +time_zone+ attribute: ./bin/rails g model user time_zone:string
#
# class User < ActiveRecord::Base
# validates :time_zone, presence: true, time_zone: true
# end
#
# Usage just with ActiveModel:
#
# class User
# include ActiveModel::Validations
# validates :time_zone, presence: true, time_zone:true
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.