Created
February 7, 2018 17:28
-
-
Save nsommer/f9791786a08efbb9a46ba8cfa541cbd8 to your computer and use it in GitHub Desktop.
ActiveModel Validator that checks whether the string value of an attribute is a valid ActiveSupport::TimeZone
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
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