通过Ruby on Rails的验证方法,验证年份的最佳方式是什么?

8

目前我有一个检查出生年份是否正确的函数:

  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_format” 看起来没有用,你确定你的代码规范吗? - apneadiving
3个回答

14

4
: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
                           }

1
正则表达式
   /\A(19|20)\d{2}\z/

我只会允许1900年至2099年之间的数字。

\A - 字符串开头

\z - 字符串结尾


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接