tracks/tracks/lib/validations.rb
bsag 4c2742f6f3 Started adding support for the Chronic library, to provide natural language date selections. You can now type phrases such as "tomorrow", "nov 10", "1 week hence", "10 days hence" and so on into the date box and these will be parsed into a valid date. I haven't managed to get proper validation working yet, but you'll get a live preview of the parsed date just below the input box.
What doesn't work yet:

* If you delete all characters in the date box, you'll get an error message. This will go away if you type more characters
* You'll get an error as above when the form is cleared and redisplayed after submission. Again, it will go away if you type anything in the box.
* Validation doesn't work, but the preview will display "Invalid date" if Chronic can't parse your phrase
* This isn't added to the edit form for actions yet.

Also partially fixed #394: the mobile interface works again, but you might get an error visiting the subsequent pages of a filtered view (i.e. viewing a single context or project). I'm not sure what's causing this, but it's on my list to fix.

git-svn-id: http://www.rousette.org.uk/svn/tracks-repos/trunk@332 a4c988fc-2ded-0310-b66e-134b36920a42
2006-10-25 15:35:08 +00:00

28 lines
No EOL
1 KiB
Ruby

ActiveRecord::Validations::ClassMethods.class_eval do
# Custom validations
# Validating a date field parsed by Chronic. If Chronic cannot parse the
# date, it returns nil
# Adapted from Stuart Rackham's custom date validation
# http://www.bigbold.com/snippets/posts/show/1548
#
def validates_chronic_date(*attr_names)
configuration =
{ :message => 'is an invalid date. Here are some valid examples: feb 23, 23 feb 06, 6 feb 2006, 2006-02-23, tomorrow, today, 5 days (hence), 1 month hence, etc.)',
:on => :save,
}
configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
# Don't let validates_each handle allow_nils, it checks the cast value.
allow_nil = configuration.delete(:allow_nil)
validates_each(attr_names, configuration) do |record, attr_name, value|
before_cast = record.send("#{attr_name}_before_type_cast")
next if allow_nil and (before_cast == '')
begin
date = Chronic.parse(before_cast.to_s).nil?
rescue
record.errors.add(attr_name, configuration[:message])
end
end
end
end