From 8f83cddd0cd4d9f746734eb267fdb7da61da482e Mon Sep 17 00:00:00 2001 From: Jake Yesbeck Date: Fri, 8 Jan 2016 17:09:18 -0800 Subject: [PATCH] Mark non Date/Time objects as invalid This should Resolve #48. Given a test model: ```ruby class TestModel attr_accessor :foo validates :foo, date: true def initialize(date) @foo = date end end ``` Behaviour before this patch: ```ruby m = TestModel.new('not a date') m.valid? => true ``` Behaviour after this patch: ```ruby m = TestModel.new('not a date') m.valid? => false ``` The only outstanding question is should a string like `2016-01-08` go through `Date.parse` or `to_date` to try and make it valid. --- lib/active_model/validations/date_validator.rb | 5 +++++ test/date_validator_test.rb | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/lib/active_model/validations/date_validator.rb b/lib/active_model/validations/date_validator.rb index 313446b..bc653ec 100644 --- a/lib/active_model/validations/date_validator.rb +++ b/lib/active_model/validations/date_validator.rb @@ -68,6 +68,11 @@ def validate_each(record, attr_name, value) return end + unless is_time?(value) + record.errors.add(attr_name, :not_a_date, options) + return + end + options.slice(*CHECKS.keys).each do |option, option_value| option_value = option_value.call(record) if option_value.is_a?(Proc) option_value = record.send(option_value) if option_value.is_a?(Symbol) diff --git a/test/date_validator_test.rb b/test/date_validator_test.rb index 3809aa3..fa25b14 100644 --- a/test/date_validator_test.rb +++ b/test/date_validator_test.rb @@ -148,6 +148,13 @@ module Validations TestRecord.new(nil).valid?.must_equal false end end + + describe 'with garbage input' do + it 'is invalid' do + TestRecord.validates(:expiration_date, date: true, allow_nil: true) + TestRecord.new('not a date').valid?.must_equal false + end + end end end