繁体   English   中英

您如何编写Rails验证,该验证以是否在表单中填写其他字段为条件?

[英]How do you write a rails validation that is conditional upon if other fields were filled out within a form?

我正在尝试在电子商务网站的结帐页面中实施可选的礼品消息表单。 我们的表格为您提供了标准的运输信息,但我希望获得该信息,因此,如果客户开始填写礼品消息的字段,则礼品消息所需的所有字段都需要进行验证。 我有4个领域

:gift_message_to-输入有关礼物送给谁的信息

:gift_message_from-礼物来自的人的名字

:gift_message_message-他们的信息

:gift_recipient_email-将会向收件人发送一封电子邮件,通知他们他们将收到礼物。 这将使用正则表达式和html5来确保它是格式正确的电子邮件地址。

我当时想创建自己的验证方法

  def order_has_gift_message_field
    order_has_gift_message_field = false
    if self.gift_message_message.to_s.size > 0 || self.gift_message_to.to_s.size > 0 ||  self.gift_message_from.to_s.size > 0 || self.gift_recipient_email.to_s.size
      order_has_gift_message_field = true
    end
    return order_has_gift_message_field
  end

并验证它

validate :order_has_gift_message_field

因此,如果用户开始输入这些字段中的任何一个,其他字段也需要填写。 但是如果他们不输入任何信息,则不会显示验证信息。 有人做过类似的事情吗? 任何建议将不胜感激。

看一下Rails指南的自定义验证

有一个示例可以像您建议的那样制作自定义验证方法。

class Invoice < ActiveRecord::Base
  validate :active_customer, on: :create

  def active_customer
    errors.add(:customer_id, "is not active") unless customer.active?
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM