Skip to content

Instantly share code, notes, and snippets.

@nsommer
Created February 7, 2018 17:28
Show Gist options
  • Save nsommer/f9791786a08efbb9a46ba8cfa541cbd8 to your computer and use it in GitHub Desktop.
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
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