Best way to test a year using the Ruby on Rails validation method?

I currently have a function to check for the correct delivery:

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

I also have a function that checks for the correct date:

  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 lower method into validates from above, and not the two checks that I have now?

+7
source share
3 answers

You should 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

+12
source
 :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 } 
+4
source

regex

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

will only allow numbers between 1900 and 2099

\ A - beginning of line

\ z - End of line

+1
source

All Articles