views:

94

answers:

1

I have a date field in a model backed form in my Rails App:

<%= f.date_select :birthday,
  {:start_year => Time.now.year,
  :end_year => 1900,
  :use_short_month => true,
  :order => [:month, :day, :year],
  :prompt => {:month => 'Month', :day => 'Day', :year => 'Year'}},
  {:class => 'year',
  :id => 'user_birthday'}
%>

It is being validated in the model code using:

validates_presence_of :birthday, :message => 'is a required field'

Unfortunately, if the user enters a partial value such as just the year, the form still submits without an error. Instead a funky date value gets written to the db. How do I make all three fields be mandatory?

I'd like to write a custom validation for this, but I don't know how to properly access the indvidual pieces of the birthday element. How can I do this?

Thanks! Moe

A: 

You could override the validate_on_create method, like the following:

class MyModel < ActiveRecord::Base
  def validate_on_create
    Date.parse(birthday)
  rescue
    errors.add_to_base("Wrong date format")
  end
end
sespindola
Date.parse won't work here since the date value isn't invalid. it's just funky. if you leave the year blank, you'll get something like "0007-01-01".
Moe
You're right.Instead of parse, you should use civil. Like this:Date.civil(birthday[:year].to_i, birthday[:month].to_i, birthday[day].to_i)That should throw an ArgumentError if any field is blank.
sespindola
Unfortunately, this didn't work either. It throws an error even if I enter all fields properly. I attempted to write a custom validation method in the model class, but I can't access the field value using `birthday[:month]` or even with `.to_i` appended.Any ideas on how to do this?
Moe