[ruby]
[rails]
[plugin]
[rails_plugin]
[ActiveRecord]
日付のvalidateって標準では実装されてないんですね。何でだろう。
$./script/plugin list
を使って、それっぽいのを探してみる。
2分で発見。やっぱり誰かが先に作ってくれてました。
http://plugins.radrails.org/directory/show/22
$./script/plugin install validates_date_time
としてインストール。
READMEより、一部抜粋。
datetime型のパラメーターが、正しくパースされなかった場合にエラーが起こる。
p = Person.new
p.date_of_birth = "1 Jan 2006"
p.time_of_birth = "5am"
p.save # true
p.date_of_birth = "30 Feb 2006"
p.save # false, 30 feb is invalid for obvious reasons
p.date_of_birth = "java is better than ruby"
p.save # false
:beforeや、:afterオプションを使う事で、日付時間の範囲を制限できる。
class Person
validates_date :date_of_birth, :before => [:date_of_death, Proc.new { 1.day.from_now_to_date}], :after => '1 Jan 1900'
validates_date :date_of_death, :before => Proc.new { 1.day.from_now.to_date }
end
p = Person.new
p.date_of_birth = '1800-01-01'
p.save # false
p.errors[:date_of_birth] # must be after 1 Jan 1900
p.date_of_death = Date.new(2010, 1, 1)
p.save # false
p.errors[:date_of_death] # must be before <1 day from now>
p.date_of_birth = '1960-03-02'
p.date_of_death = '2003-06-07'
p.save # true
もちろんメッセージも指定可能。
class Person
validates_date :date_of_birth, :after => Date.new(1900, 1, 1), :before => Proc.new { 1.day.from_now.to_date }, :before_message => 'Ensure it is before %s', :after_<
end