1

I use time_select with a prompt ("Choose hours"...) and would like to make sure, the user actually enters a valid time. But if the form is submitted without a time being selected (so with the empty prompt options selected) I don't get any errors from my validations.

My Validation:

validates :start_time, :presence => true, :allow_nil => false, :allow_blank => false

The reason is that rails turns the input from the time_select fields automatically into this date, when they are empty:

0001-01-01 00:00:00

Is there a nice way to prevent this from happening?

Thanks!

Ole Spaarmann
  • 15,845
  • 27
  • 98
  • 160
  • This would bypass the validation a it but what if you did `<%= f.time_select :field, :value => Time.now %>` [with other options you want of course]? It would at least capture the current time. Or you could set a time variable in your controller, e.g. `@time_entered = [some time]`, and then use `@time_entered` in place of `Time.now`. – ScottJShea Mar 01 '12 at 10:42
  • 1
    I actually did that before. But the problem here is with the usability. If I set a default time of e.g. 6pm people will forget to select the correct time (because the validation never fails). That is the reason why I'm looking for a different solution. – Ole Spaarmann Mar 01 '12 at 10:49
  • Yeah... it was a hacky way of doing it to be sure. I just posted an answer I hope works for you. – ScottJShea Mar 01 '12 at 10:51

1 Answers1

1

If you want to enforce a validation it looks like, at least from this SO Post and this SO Post, you would want to do a custom validation.

class Whatever < ActiveRecord::Base
    validate :time_scope
    ...
    private
    def time_scope
      if Whatever.where(<pick the record entered>).time == "0001-01-01 00:00:00"
        errors.add(:time, "Oh no you didn't enter that garbage time on my watch!")
      end
    end
end

Obviously this is a silly example but I hope it gets the idea across.

Community
  • 1
  • 1
ScottJShea
  • 7,041
  • 11
  • 44
  • 67