Rails:如何为错误的日期添加验证,例如11月31日和6月31日。我使用过:date作为我的列类型

时间:2012-11-27 15:57:46

标签: ruby-on-rails ruby

我的表格看起来像这样 视图/简档/ _form

<div class="field2">
<%= f.label :purchase_date, "Date this horse was purchased" %><br />
<%= f.date_select :purchase_date %>
</div>

<div class="field2">
<%= f.label :owner_name, "Owner Name" %><br />
<%= f.text_field :owner_name %>
 </div>

我在我的模型/ profile.rb中添加了哪些验证

验证:purchase_date ????????

2 个答案:

答案 0 :(得分:1)

你想要exclusion validation。它看起来像这样:

# Made it a constant, but could also be in a method.
EXCLUSION_DATE = [Date.new(2012,1,1), Date.new(2012,2,1)]
validates :purchase_date, :exclusion => { :in => EXCLUSION_DATES }

您也可以随时添加自己的自定义验证:

validate :check_purchase_date # Name it whatever you want

private
  def check_purchase_date
    exclusion_dates = [Date.new(2012,1,1), Date.new(2012,2,1)]
    if exclusion_dates.include?(self.purchase_date)
      self.errors.add(:purchase_date, "cannot be on a reserved date.")
    end
  end

答案 1 :(得分:0)

为什么不让用户从jquery datepicker中选择,以便你可以直接消除tje问题?