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

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


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


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


regex

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

will only only allow numbers between 1900 e 2099

\A - Start of string

\z - End of string