0

If user inserts a value that is not accepted to the to_date method, e.g. "some gibberish", it returns:

"ArgumentError: invalid date"

How could I construct a custom validation that returns an validation message to user and doesn't halts the application?

I was thinking that reusing the code from another answer would be a good idea, but I don't know how to apply it to to_date.

validate do
  self.errors[:start] << "must be a valid date" unless DateTime.parse(self.start) rescue false  
end
Community
  • 1
  • 1
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

2 Answers2

2

It could be achieved with rescue, and then addes to errors

class Post < ActiveRecord::Base

  validate do |post|
    begin
      Date.parse(post.date)
    rescue ArgumentError
      errors.add(:date, "must be a valid date")
    end
  end

## Another way

  validate do |post|
    # make sure that `date` field in your database is type of `date`
    errors.add(:date, "must be a valid date") unless post.date.try(to_date) 
  end
end
itsnikolay
  • 17,415
  • 4
  • 65
  • 64
  • I'm trying to make a custom validation method out of your code, but I don't get nowhere.. :/ – Fellow Stranger Sep 23 '14 at 19:35
  • I'm appearantly doing something wrong. With the second solution I'm receiving "NameError: undefined local variable or method" and with the first: "TypeError: no implicit conversion of nil into String". But it looks correct what you have suggested so I will just try to research my code a bit more. – Fellow Stranger Sep 23 '14 at 19:57
  • Seriously, if you pass by Stockholm any day, I owe you a dinner! Thank you very much. – Fellow Stranger Sep 23 '14 at 20:36
  • 1
    @Numbers heh ;) too cold for me, anyway thanks for the cool offer. :) – itsnikolay Sep 23 '14 at 20:40
0

Rather than writing your own validation (and having to write tests for it!) I suggest the validates_timeliness gem

Using it is as simple as

  validates_date :attribute_name
Abraham Chan
  • 629
  • 3
  • 12