Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to validate year via Ruby on Rails validates method?

Currently I have a function to check if the birthyear is correct:

  validates :birth_year, presence: true,
            format: {with: /(19|20)\d{2}/i }

I also have a function that checks if the date is correct:

  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

Is it possible to combine the bottom method into the validates at the top instead of the two validates I have now?

like image 845
perseverance Avatar asked Sep 26 '12 23:09

perseverance


3 Answers

You should be able to do something like this:

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

Take a look at: http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates

like image 89
Moriarty Avatar answered Nov 13 '22 10:11

Moriarty


: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
                           }
like image 27
Eru Avatar answered Nov 13 '22 12:11

Eru


regex

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

will only only allow numbers between 1900 e 2099

\A - Start of string

\z - End of string

like image 35
Emmanuel P. Avatar answered Nov 13 '22 12:11

Emmanuel P.