I have an application that requires users to be in a specific age group,
or above a certain age. For simplicity sake lets say they have to be at
least 18.
This is my most recent attempt to produce the desired result:
validates_exclusion_of :birthday, :in => Range.new(Date.today,
Date.parse( (18.years.ago).strftime(’%Y/%m/%d’) )),
:message => “does not meet Terms of Service requirements”
" Date.parse( (16.years.ago).strftime(’%Y/%m/%d’) ) " works as expected
in console, however the validation always results in a true state.
Also, I believe this opens a condition where a user could set their
birthday in the future. I would like to do this without plugins, it
seems simple enough.
I have an application that requires users to be in a specific age group,
or above a certain age. For simplicity sake lets say they have to be at
least 18.
validates_each :birthday do |record, attr, value|
record.errors.add attr, ‘does not meet Terms of Service requirements
(over 18)’ if value > (18.years.ago).to_date
end
Just a quick note, you need to be careful assigning :before and :after
parameters like that because they are only evaluated once. As time
passes
you may notice problems with your date ranges being wrong (unless your
server is restarted). Instead of passing a date object to :after, use a
proc
that returns a date as it will be evaluated for each validation.
If you change your mind about the plugins, i’d recommend
valdiates_date_time
validates_date :date_of_birth,
:after => Date.new(Date.today.year - 127,
Date.today.month,
Date.today.mday),
:before => Date.new(Date.today.year - 18,
Date.today.month,
Date.today.mday),
:after_message => ‘Birthdate of %s is
invalid’,
:before_message => ‘have to be 18’
Thanks Alex, I found an easy way to handle this using validates_each
validates_each :birthday do |record, attr, value|
record.errors.add attr, ‘does not meet Terms of Service requirements
(over 18)’ if value > (18.years.ago).to_date
end