在 Ruby on Rails 中验证日期的最佳方法是什么?我需要确保“生日”是一个日期,小于 125 年前并且不在未来(今天可以)。
我试过三种方法:
1) date_validator gem
我使用了以下代码(安装 gem 之后):
validates :birthday,
date: {
after: Proc.new {Time.now - 125.years}, message: :after,
before: Proc.new {Time.now}, message: :cannot_be_in_the_future
}
这有效除了我可以将日期设置为数字 12 并通过验证。
2) 在自定义验证方法中检查日期是否在日期范围内,如下所示:
from = 125.years.ago.to_date
to = Time.now.to_date
unless (from..to).include? birthday
errors.add(:birthday, :custom_error_msg)
end
这很好用并通过了我的所有测试,但缺点是您只会收到一条错误消息。对于 future 日期、时间太久以前以及输入不是日期的情况,我希望有单独的错误消息。
3) 在自定义验证方法中进行多次检查,如下所示:
begin
birthday.to_date
rescue
errors.add(:birthday, "must be a date")
else
if birthday > Time.now
errors.add(:birtday, "cannot be in the future")
elsif birthday < Time.now - 125.years
errors.add(:birthday, "cannot be over 125 years ago")
end
end
这也通过了我的所有测试,并且我收到了如上所述的不同消息。
所以我想知道,这是最好的方法吗?是否可以对其进行改进(除了错误消息文本需要修改)?
谢谢
最佳答案
对于这个简单的验证,我认为下面的 ruby 代码就足够了!
请检查:
validate :is_valid_dob?
private
def is_valid_dob?
if((birthday.is_a?(Date) rescue ArgumentError) == ArgumentError)
errors.add(:birthday, 'Sorry, Invalid Date of Birth Entered.')
end
end
关于ruby-on-rails - Rails 4 中的最佳日期验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27943700/