Search code examples
ruby-on-railsruby-on-rails-4ruby-on-rails-5simple-formruby-on-rails-6

How to restrict the date field in a simple_form_for


I am using a simple date_field in a simple_form_for and its working fine. I just need to tweek it so that it only shows dates from 12 years ago and before. I.E no one should be able to enter a date within the last 12 years.

Here is the line of code I have.

<%= f.date_field :birthday, start_year: Time.now.year - 100, 
          end_year: Time.now.year-12, :default => @profile.birthday %>

The "start_year: " and "end_year" haven't worked for me (maybe I am using them wrong?). Users can still enter invalid dates.

Does anyone know of any other things i should try?


Solution

  • Use validation in your model.

     validates_inclusion_of :birthday, 
       in: Date.civil(1950, 1, 1)..Date.today-14.years,
       message: "Must be between 1950 and 2000 and now"
    

    For sure this is an example and you can set it to pretty much whatever fits your needs.