2

I'm adding validations to a model with a start column that is typed as datetime

Currently I only use the date_select form helper, but have left the column typed to datetime in case I decide I want to use the time value in the future.

I am currently using:

validates :start, :presence => true

But I want to know if there is a :format => that will ensure I'm getting a date passed in. I know it's unlikely that someone would change the select boxes around, but I figure you can't be too careful, right?

lucapette
  • 20,564
  • 6
  • 65
  • 59
Rapture
  • 1,876
  • 10
  • 23
  • 42

2 Answers2

11

It depends what date formats you want to accept.

f.e.

validates :start, :presence => true, :format => /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/

for dd-mm-yyyy as dateformat.

Google for date regexp!

Since my answer was downvoted i give it another try:

   validate do
      self.errors[:start] << "must be a valid date" unless (DateTime.parse(self.start) rescue false)
   end
BvuRVKyUVlViVIc7
  • 11,641
  • 9
  • 59
  • 111
2

You may want to check out validates_timeliness gem.

This gem enables some useful date and time-relations validations. In your case, you might use it to validate your start attribute like this:

class Task < ActiveRecord::Base
  validates_datetime :start
  # or
  validates :start, presence: true, timeliness: {type: :datetime}
end
dgilperez
  • 10,716
  • 8
  • 68
  • 96
  • @kleopatra thanks for the advice. I extended the answer to refer to the particular context of the question and making it stand-alone. Cheers! – dgilperez Aug 15 '13 at 11:44