Ruby on rails 通过RubyonRails验证方法验证年份的最佳方法?
目前我有一个功能来检查生日是否正确:Ruby on rails 通过RubyonRails验证方法验证年份的最佳方法?,ruby-on-rails,Ruby On Rails,目前我有一个功能来检查生日是否正确: 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.
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, 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
是否可以将底部方法合并到顶部的
验证中,而不是我现在使用的两个验证中?您应该能够执行以下操作:
:birth_year, presence: true,
format: {
with: /(19|20)\d{2}/i
}
numericality: {
only_integer: true,
greater_than_or_equal_to: 1900,
less_than_or_equal_to: Date.today.year
}
validates :birth_year,
presence: true,
inclusion: { in: 1900..Date.today.year },
format: {
with: /(19|20)\d{2}/i,
message: "should be a four-digit year"
}
看看:regex
/\A(19|20)\d{2}\z/
只允许1900和2099之间的数字
\A-字符串的开头
\z-字符串结尾出生年份格式
似乎没用,你的代码规范了吗?