How do I validate a date in rails?

2019-01-04 09:28发布

I want to validate a date in my model in Ruby on Rails, however, the day, month and year values are already converted into an incorrect date by the time they reach my model.

For example, if I enter February 31st 2009 in my view, when I use Model.new(params[:model]) in my controller, it converts it to "March 3rd 2009", which my model then sees as a valid date, which it is, but it is incorrect.

I would like to be able to do this validation in my model. Is there any way that I can, or am I going about this completely wrong?

I found this "Date validation" that discusses the problem but it never was resolved.

9条回答
啃猪蹄的小仙女
2楼-- · 2019-01-04 10:15

A bit late here, but thanks to "How do I validate a date in rails?" I managed to write this validator, hope is useful to somebody:

Inside your model.rb

validate :date_field_must_be_a_date_or_blank

# If your field is called :date_field, use :date_field_before_type_cast
def date_field_must_be_a_date_or_blank
  date_field_before_type_cast.to_date
rescue ArgumentError
  errors.add(:birthday, :invalid)
end
查看更多
姐就是有狂的资本
3楼-- · 2019-01-04 10:16

If you want Rails 3 or Ruby 1.9 compatibility try the date_validator gem.

查看更多
放我归山
4楼-- · 2019-01-04 10:16

You can validate the date and time like so (in a method somewhere in your controller with access to your params if you are using custom selects) ...

# Set parameters
year = params[:date][:year].to_i
month = params[:date][:month].to_i
mday = params[:date][:mday].to_i
hour = params[:date][:hour].to_i
minute = params[:date][:minute].to_i

# Validate date, time and hour
valid_date    = Date.valid_date? year, month, mday
valid_hour    = (0..23).to_a.include? hour
valid_minute  = (0..59).to_a.include? minute
valid_time    = valid_hour && valid_minute

# Check if parameters are valid and generate appropriate date
if valid_date && valid_time
  second = 0
  offset = '0'
  DateTime.civil(year, month, mday, hour, minute, second, offset)
else
  # Some fallback if you want like ...
  DateTime.current.utc
end
查看更多
登录 后发表回答