目前我有一个功能来检查分娩年份是否正确:
validates :birth_year,presence: true,format: {with: /(19|20)\d{2}/i }
我还有一个检查日期是否正确的函数:
validate :birth_year_format private def birth_year_format errors.add(:birth_year,"should be a four-digit year") unless (1900..Date.today.year).include?(birth_year.to_i) end
解决方法
你应该可以做这样的事情:
validates :birth_year,inclusion: { in: 1900..Date.today.year },format: { with: /(19|20)\d{2}/i,message: "should be a four-digit year" }
看看:http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates