I have an Active Record model that contains attributes: expiry_date. How do I go about validating it such that it is after today(present date at that time)? I am totally new to
I took @dankohn answer, and updated to be I18n ready. I also removed the blank
test, because that's not the responsibility of this validator, and can easily be enabled by adding presence: true
to the validates call.
The updated class, now named in_future
, which I think is nicer than not_in_past
class InFutureValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add(attribute, (options[:message] || :in_future)) unless in_future?(value)
end
def in_future?(date)
date.present? && date > Time.zone.today
end
end
Now add the in_future
key to your localization file.
For all fields under errors.messages.in_future
, e.g. for Dutch:
nl:
errors:
messages:
in_future: 'moet in de toekomst zijn'
Or per field under activerecord.errors.models.MODEL.attributes.FIELD.in_future
, e.g. for the end_date
in a Vacancy
model in Dutch:
nl:
activerecord:
errors:
models:
vacancy:
attributes:
end_date:
in_future: 'moet in de toekomst zijn'