Ok I have 3 select boxes for selecting date of birth.
I have constants setup in my User model to provide months, years etc..
Anyway I can successfully validate these select boxes separately.
What I want to do is combine the :day, :month and :year and store in :birthday and validate the whole date as one so I can return 1 error rather than 3 separate ones.
Also doing this will make it easier to store the validated date in my birthday field in my database.
Part of my form
<td> <%= f.input :day, :required => false, :label => "Birthday: " , :prompt => "Day", :collection => User::DAYS %></td>
<td> <%= f.input :month, :label => false, :prompt => "Month", :collection => User::MONTHS %> </td>
<td> <%= f.input :year, :label => false, :prompt => "Year", :collection => User::YEAR_RANGE %> </td>
Part of User model
MONTHS = ["January", 1], ["February", 2], ["March", 3], ["April", 4], ["May", 5], ["June", 6], ["July", 7], ["August", 8], ["September", 9], ["October", 10], ["November", 11], ["December", 12] # finish this DAYS = 1..31 # finish this START_YEAR = Time.now.year - 106 END_YEAR = Time.now.year YEAR_RANGE = START_YEAR..END_YEAR
class User < ActiveRecord::Base attr_accessor :day, :month, :year
validates_presence_of :day, :message => 'What day in a month was you born?'
validates_presence_of :month, :message => 'What month was you born?'
validates_presence_of :year, :message => 'What is your year of birth?'end
I would change the column to datetime (date never seems to work for me).
t.datetime :birthday
Then use a date_select in your view.
<div class="field">
<%= f.label :birthday %><br />
<%= f.date_select :birthday, :include_blank => true, :start_year => Time.now.year - 70 %>
</div>
Then in your model validate birthday presence.
validates_presence_of :birthday
If you need to make sure the birthday is older than a certain age, write a custom validation.
validate :of_certain_age
private
def of_certain_age
if self.birthday
errors.add(:base, 'You need to be at least 18.') if self.birthday > 18.years.ago
end
end