【问题标题】:rails custom date validationrails自定义日期验证
【发布时间】:2016-06-30 22:29:58
【问题描述】:

在表单中,用户必须选择月份和年份。我想确保日期不是基于月份的未来。因此,假设当前日期是 07/01/2016,在这种情况下,用户应该能够选择 07/2016,但不能选择 08/2016。

验证似乎有效,但看起来不太好。有没有更简单的方法 实现这个?

validate :founded_in_the_past

def founded_in_the_past
  if founded && ((founded.month > Date.current.month && founded.year == Date.current.year) 
    && founded.year > Date.current.year)
      errors.add :base, "Founding date must be in the past."
  end
end

【问题讨论】:

  • 该条件看起来总是错误的:founded.year == Date.current.yearfounded.year > Date.current.year。我假设您的意思是最后一个 &&||
  • 潜伏者你是对的。最后一个应该是||

标签: ruby-on-rails validation date activerecord


【解决方案1】:

您不使用月份和年份创建日期对象来直接比较日期,而不是检查月份和年份。

validate :founded_in_the_past

def founded_in_the_past
  if founded && (Date.new(founded.year, founded.month, 1) > Date.current)
    errors.add :base, "Founding date must be in the past."
  end
end

在您的代码中,如果您选择年份为2017 和月份为5 - 它将允许选择此日期

founded && ((founded.month > Date.current.month && 
  founded.year == Date.current.year) && 
  founded.year > Date.current.year)

成立 = 真

founded.month > Date.current.month = false

founded.year == Date.current.year = false

founded.year > Date.current.year = true

如果我们根据您的情况进行映射,您的情况将如下所示

真&&((假&&假)&&真)

这将返回 false 并允许用户选择未来日期

【讨论】:

  • Sampat 你是对的,我用错了运算符。最后一个应该是|| 而不是&&
【解决方案2】:

您可以使用>= 例如删除一个条件

if founded && (founded.month > Date.current.month && founded.year >= Date.current.year)

【讨论】:

  • 感谢塔林的回答!不应该只是 founded.month > Date.current.month 而不是 founded.month >= Date.current.month 吗?当前月份应与日期无关
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-11
相关资源
最近更新 更多