diff --git a/lib/validates_timeliness/validator.rb b/lib/validates_timeliness/validator.rb index edeccae..f9d5ba2 100644 --- a/lib/validates_timeliness/validator.rb +++ b/lib/validates_timeliness/validator.rb @@ -44,23 +44,29 @@ module ValidatesTimeliness value = parse(raw_value) if value.is_a?(String) || options[:format] value = type_cast_value(value, @type) - return record.errors.add(attr_name, :"invalid_#{@type}") if value.blank? + if value.blank? + return add_error(record, attr_name, :"invalid_#{@type}") + end @restrictions_to_check.each do |restriction| begin restriction_value = type_cast_value(evaluate_option_value(options[restriction], record), @type) - unless value.send(RESTRICTIONS[restriction], restriction_value) - return record.errors.add(attr_name, restriction, :message => options[:"#{restriction}_message"], :restriction => format_error_value(restriction_value)) + return add_error(record, attr_name, restriction, format_error_value(restriction_value)) end rescue => e unless ValidatesTimeliness.ignore_restriction_errors - record.errors[attr_name] = "Error occurred validating #{attr_name} for #{restriction.inspect} restriction:\n#{e.message}" + add_error(record, attr_name, "Error occurred validating #{attr_name} for #{restriction.inspect} restriction:\n#{e.message}") end end end end + def add_error(record, attr_name, message, value=nil) + message_options = { :message => options[:"#{message}_message"], :restriction => value } + record.errors.add(attr_name, message, message_options) + end + def format_error_value(value) format = I18n.t(@type, :default => DEFAULT_ERROR_VALUE_FORMATS[@type], :scope => 'validates_timeliness.error_value_formats') value.strftime(format) diff --git a/spec/validates_timeliness/validator_spec.rb b/spec/validates_timeliness/validator_spec.rb index 8554b58..9a2f117 100644 --- a/spec/validates_timeliness/validator_spec.rb +++ b/spec/validates_timeliness/validator_spec.rb @@ -190,11 +190,14 @@ describe ValidatesTimeliness::Validator do end context "custom error message" do + it 'should be used for invalid type' do + Person.validates_date :birth_date, :invalid_date_message => 'custom invalid message' + invalid!(:birth_date, 'asdf', 'custom invalid message') + end - it 'should be used for failing restriction' do + it 'should be used for invalid restriction' do Person.validates_date :birth_date, :before => Time.now, :before_message => 'custom before message' invalid!(:birth_date, Time.now, 'custom before message') end - end end