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顶部而不是我现在拥有的两个验证?

4

3 回答 3

14

你应该能够做这样的事情:

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"
  }

看看:http ://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates

于 2012-09-26T23:26:00.810 回答
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
                           }
于 2012-09-26T23:25:47.347 回答
1

正则表达式

   /\A(19|20)\d{2}\z/

只允许 1900 e 2099 之间的数字

\A - 字符串的开始

\z - 字符串结束

于 2014-09-25T16:43:26.030 回答