【问题标题】:How to validate radio button is selected?如何验证单选按钮被选中?
【发布时间】:2016-03-08 21:52:38
【问题描述】:

我正在尝试验证是否选择了“从不”单选按钮,或者选择了带有日期的“日期”(带有 datepicker),因此是:expiry_date

:expiresstring type

:expiry_datedate type

      f.input :expires, as: :radio, :collection => ["Never", "Date"]
      f.input :expiry_date, as: :string, :wrapper_html => { :class => "date_picker"}

这是我目前的验证。

  validates :expires,
  inclusion: { in: ["Never", "Date"],
  presence: { message: "none selected"}}
  validates :expiry_date, presence: true

【问题讨论】:

    标签: ruby-on-rails-4 activeadmin formtastic


    【解决方案1】:

    您可以使用custom validation

    class Food < ActiveRecord::Base
      validate :has_expiry_date
    
      def has_expiry_date
        if expires == "Date" && !expiry_date.present?
          errors.add(:expiry_date, 'needs to be present if food expires')
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2013-10-02
      • 2012-10-10
      • 2023-04-06
      • 2013-06-13
      • 1970-01-01
      • 2016-02-15
      • 2015-09-01
      • 2012-12-01
      相关资源
      最近更新 更多