2

I think this is a simple question. In my app, I have a model where users select a 'start' date and a 'stop' date when submitting a new record. The dates are only the years, excluding month and day.

I just want to write a validation to ensure that the stop date is greater than the start date, so you can't submit something that started in 2012 and ended in 2008. How would I do that?

My form fields are below:

<%= select_year Date.today, start_year: Time.now.year, end_year: Time.now.year - 95, field_name: :start %>

<%= select_year Date.today, start_year: Time.now.year, end_year: Time.now.year - 95, field_name: :stop %>
1
  • Aside from the answers below, consider swapping the values if someone puts in an end smaller then a start.
    – baash05
    Jun 6, 2013 at 3:53

1 Answer 1

4

If you want to do a server side validation, you could add validation to your model

validate :stop_date


def stop_date
  errors.add(:stop, "stop date cannot be older than start date") if stop < end
end

You could populate the errors on the view.

2
  • I think the implication here is that you'b be better off testing this on input with some javascript. :)
    – baash05
    Jun 6, 2013 at 3:51
  • Thanks I agree. I am using the client side validations gem so I will try to figure out how to use that for a javascript validation
    – Zephyr4434
    Jun 6, 2013 at 3:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.