Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 通过RubyonRails验证方法验证年份的最佳方法?_Ruby On Rails - Fatal编程技术网

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-字符串结尾

出生年份格式
似乎没用,你的代码规范了吗?