I have four date_time fields in my model in Rails app. I want to apply the same validation method to them, so that only a valid date time could be accepted. Validation metho
def self.validate_is_valid_datetime(field)
validate do |model|
if model.send("#{field}?") && ((DateTime.parse(model.send(field)) rescue ArgumentError) == ArgumentError)
model.errors.add(field, 'must be a valid datetime')
end
end
end
validate_is_valid_datetime :datetime_field
Best solution is to create your own validator:
class MyModel < ActiveRecord::Base
include ActiveModel::Validations
class DateValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << "must be a valid datetime" unless (DateTime.parse(value) rescue nil)
end
end
validates :datetime_field, :presence => true, :date => true
validates :another_datetime_field, :presence => true, :date => true
validates :third_datetime_field, :presence => true, :date => true
end
UPD
you can share same validations this way:
validates :datetime_field, :another_datetime_field, :third_datetime_field, :presence => true, :date => true