【问题标题】:Ruby on Rails: Validating the Month and Year of a cardRuby on Rails:验证卡片的月份和年份
【发布时间】:2021-09-10 18:45:23
【问题描述】:

我在我的应用程序中使用卡详细信息并且我想验证这些信息,以便每当用户添加他/她的卡详细信息时,它都会显示过去一个月和一年的错误消息。

这是我正在使用的代码 -

.task-name-container.required
        %label Expiration Date
        = f.input :month, collection: %w(1 2 3 4 5 6 7 8 9 10 11 12), label: false, required: true, input_html: { class: "task-select #{'error' unless f.object.errors[:expiration_date].empty?}" }
        = f.input :year, collection: (Date.today.year..(Date.today.year+10)), label: false, required: true, input_html: { class: "task-select year #{'error' unless f.object.errors[:expiration_date].empty?}" }

目前此代码允许用户添加过去的月份。

有人知道如何根据 haml 文件中的条件添加该错误消息吗?

请帮忙!谢谢。

【问题讨论】:

  • 什么是“卡片”?你想验证什么?请说明您尝试了什么,您的预期行为是什么,等等。
  • @engineersmnky 这里卡的意思是“信用卡/借记卡”,我正在尝试对月份和年份字段进行验证,以便用户无法添加卡的过去日期。
  • 我会将这些信息添加到问题中。此外,由于存在无数合规问题和信用卡处理的其他细微差别,我强烈建议您不要自己这样做。大多数信用卡处理网关和票据交换所将通过 API 或其他通信方法“为您”验证此信息。

标签: ruby-on-rails validation haml


【解决方案1】:

一种解决方案可能是向类添加验证(假设它是 Card):

class Card
  validate :is_past?

  private

  def is_past?
    submitted_date = Date.new(year, month).end_of_month
    today = Date.current

    errors.add :expiration_date, "Your card is expired" if today > submitted_date
  end
end

【讨论】:

  • 信用卡在到期月份的月底到期Date.new,只有月份和年份将返回月初。例如如果我的卡在“06/2021”到期,您今天的验证将显示我的卡已过期,但尚未到期。
  • 谢谢,@engineersmnky。此外,年和月存在检查。
  • 你应该检查时间而不是日期:reference
猜你喜欢
  • 2018-09-23
  • 2011-02-02
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 2018-04-27
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多