Ruby on rails 如何验证开始日期和结束日期?
在Rails中,验证结束日期不在开始日期之前,而开始日期在结束日期之后的最佳方法是什么 我的视图控制器中有:Ruby on rails 如何验证开始日期和结束日期?,ruby-on-rails,ruby-on-rails-3,validation,Ruby On Rails,Ruby On Rails 3,Validation,在Rails中,验证结束日期不在开始日期之前,而开始日期在结束日期之后的最佳方法是什么 我的视图控制器中有: <tr> <td><%= f.label text="Starts:" %></td> <td><%= f.datetime_select :start_date, :order => [:day, :month, :year]%></td> </tr> <tr&g
<tr>
<td><%= f.label text="Starts:" %></td>
<td><%= f.datetime_select :start_date, :order => [:day, :month, :year]%></td>
</tr>
<tr>
<td><%= f.label text="Ends:" %></td>
<td><%= f.datetime_select :end_date,:order => [:day, :month, :year]</td>
</tr>
[:日、月、年]]>
[:天,月,年]
我希望它能弹出一个有意义的信息
我想创建一个通用方法,它包含两个参数:开始日期和结束日期,然后我可以在我的viewcontroller中调用它们<上面代码中的代码>fx。或者,我需要改用jQuery吗?如果需要客户端验证,请使用jQuery 或者在rails中,为了验证服务器端,我想您可以创建自己的
def date_validation
if self[:end_date] < self[:start_date]
errors[:end_date] << "Error message"
return false
else
return true
end
end
def日期\u验证
如果self[:结束日期] 错误[:end_date]避免客户端验证,因为它只验证客户端。。。
使用内置的rails验证程序
validates :start_date, presence: true, date: { after_or_equal_to: Proc.new { Date.today }, message: "must be at least #{(Date.today + 1).to_s}" }, on: :create
validates :end_date, presence: true
@亚博伊奎
客户端验证可以工作并避免对服务器的影响
问题还在于结束日期在开始之后,因此验证还应说明
validates :end_date, presence: true, date: { after_or_equal_to: :start_date}
建议
on: :create
结束日期验证不正确;从逻辑上讲,这也应该在编辑上运行
我根据简洁的语法进行了投票。清晰明了(并在控制之下?)
我发现这是最清楚的:
在您的模型中
验证是否存在:开始日期、:结束日期
验证:结束日期在开始日期之后
#######
私有的
#######
定义结束日期在开始日期之后
如果结束日期为空,则返回?||开始日期。空白?
如果结束日期<开始日期
错误。添加(:结束日期,“不能早于开始日期”)
结束
结束
要使用验证:dt_end,:date=>{:after_或_equal_to=>:dt_start}
您需要一个日期验证程序,如下所示:
class DateValidator > ActiveModel::Validator
def validate(record)
the_end = record.dt_end
the_start = record.dt_start
if the_end.present?
if the_end < the_start
record.errors[:dt_end] << "The end date can't be before the start date. Pick a date after #{the_start}"
end
end
end
end
类DateValidator>ActiveModel::Validator
def验证(记录)
_end=record.dt_end
_start=record.dt_start
如果你结束了,现在呢?
如果_结束<_开始
record.errors[:dt_end]为什么需要从date_validation
返回真值?这个答案可读性很强,但它需要date_validator
validation gem。它在vanillarrails中不可用。是的,上面的代码是它将抛出错误的代码块。
class DateValidator > ActiveModel::Validator
def validate(record)
the_end = record.dt_end
the_start = record.dt_start
if the_end.present?
if the_end < the_start
record.errors[:dt_end] << "The end date can't be before the start date. Pick a date after #{the_start}"
end
end
end
end