简体   繁体   中英

Rails - how to validate one field against another for dates

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 %>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM