Ruby on rails Rails:如何为错误的日期(如11月31日和6月31日)添加验证。我已使用:date作为我的列类型
我有一张像这样的表格 视图/配置文件/_表格Ruby on rails Rails:如何为错误的日期(如11月31日和6月31日)添加验证。我已使用:date作为我的列类型,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一张像这样的表格 视图/配置文件/_表格 <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 N
<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>
我应该在model/profile.rb中添加什么验证
验证:purchase_date?????例如,为什么不让用户从jquery datepicker中进行选择,以便您可以立即消除tje问题?您想要的。看起来是这样的:
# 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
你可以很容易地使用jquery或html5 datepicker。@MuhamamdAwais:但这些都无助于服务器端验证,如果你没有进行服务器端验证,那么你就完全错了。如果有人直接向更新URL发送帖子,或者JS被阻止并输入任何日期,那该怎么办?你的代码肯定能正常工作。是否有一种方法可以对多个日期列执行此操作,而不必对每个列重复相同的代码。基本上,我是说我希望对不止一列进行验证。例如:购买日期和:接种日期