我有一个字段为:teacher_birthday的Teacher模型。我从视图(单个文本框)中获取:teacher_birthday。我希望确保输入日期具有这样的格式- dd.mm.yyyy (我的意思是我想确保,输入日期12.24.1991将不会保存在数据库中,因为这样的日期是错误的),并且该日期存在。另外,我想在模型中这样做。这个是可能的吗?
发布于 2012-03-20 20:57:22
试试的gem吧。它有非常灵活的日期解析,包括您正在寻找的内容:
[11] pry(main)> require 'chronic'
=> true
[12] pry(main)> Chronic.parse('24.12.1991'.gsub('.','-'))
=> 1991-12-24 12:00:00 -0700发布于 2012-03-20 20:55:40
声明要在模型中调用的验证方法,然后定义此方法。下面的代码应该可以大致满足您的需求:
validate :validate_teacher_birthday
private
def validate_teacher_birthday
errors.add("Teacher birthday", "is invalid.") unless (check_valid_date && valid_date_format)
end
def valid_date_format
self.teacher_birthday.match(/[0-9][0-9].[0-9][0-9].[0-9][0-9][0-9][0-9]/)
end
def check_valid_date
begin
parts = self.teacher_birthday.split(".") #contains array of the form [day,month,year]
Date.civil(parts[2].to_i,parts[1].to_i,parts[0].to_i)
rescue ArgumentError
#ArgumentError is thrown by the Date.civil method if the date is invalid
false
end
endhttps://stackoverflow.com/questions/9786943
复制相似问题