[Ruby on Rails] 'ValidatesTimeliness' for Date and Time Validation
For date and time validation in Ruby on Rails, I recommend the ValidatesTimeliness gem.
It seems to work with not only ActiveRecord but also Mongoid.
・adzap/validates_timeliness · GitHub
After installing the validates_timeliness gem, set up minimum Japanese error messages.
# config/locales/model.ja.yml
ja:
activerecord:
errors:
messages:
invalid_date: は正しい形式で入力してください。
invalid_time: は正しい形式で入力してください。
invalid_datetime: は正しい形式で入力してください。
Basic setup is just this, then you can set validation with validates_datetime etc. in the model.
# app/models/article.rb
class Article < ActiveRecord::Base
validates_datetime :published_at
validates_date :published_date
validates_time :published_time
end
If the default date and time validation formats aren’t sufficient, you can add your own custom defined formats.
Turn on Plugin Parser with config.use_plugin_parser = true and add formats with config.parser.add_formats.
# config/initializers/validates_timeliness.rb
ValidatesTimeliness.setup do |config|
config.use_plugin_parser = true
config.parser.add_formats(:time, "%H:%M")
end
The above setting allows Time formats like “01:23”.
For more detailed information, check the Wiki.
・Plugin Parser · adzap/validates_timeliness Wiki
ValidatesTimeliness uses timeliness for Date/time parser, so you can check default formats from the timeliness page.
・timeliness/README.rdoc at master · adzap/timeliness · GitHub
ValidatesTimeliness is very convenient.
I think date and time formats are universal, so it would be nice if they were included by default in Rails. I wonder why they’re not?
That’s all from the Gemba.