Low fire danger web development
Low Fire Danger develops web applications for businesses and startups. We design, engineer and develop user experiences to make your web application a pleasure to use.
We will also help you with your business and strategise your online presence. Giving you advice and guiding you through every step, from conception to execution. Lets talk: contact@lowfiredanger.com.au

Validate Timezones in Ruby on Rails

Rails makes it too simple to allow users to specify their timezone. All you have to do is add the following to your form:

_form.html.erb
1
2
3
# ..
<%= f.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones %>
# ..
user.rb
1
2
3
# ..
field :time_zone, :type => String
# ..

Now you can see a very nice select element with all the timezones the world has to offer. In the above example, the US timezones will show before the rest of the world. But what do you do to validate the timezones? You just have to drop the below in to your model.

user.rb
1
2
3
# ..
validates_inclusion_of :time_zone, :in => ActiveSupport::TimeZone.zones_map { |m| m.name }, :message => "is not a valid Time Zone"
# ..

Simple!!