简体   繁体   English

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

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

I am trying to implement a optional gift messaging form that is within our checkout page for an e-commerce site. 我正在尝试在电子商务网站的结帐页面中实施可选的礼品消息表单。 Our form has you standard shipping information but I would like to have it so if a customer starts filling out the fields for the gift message, all the fields that are required for the gift message would require validation. 我们的表格为您提供了标准的运输信息,但我希望获得该信息,因此,如果客户开始填写礼品消息的字段,则礼品消息所需的所有字段都需要进行验证。 I have 4 fields 我有4个领域

:gift_message_to -- enter information about who the gift is for :gift_message_to-输入有关礼物送给谁的信息

:gift_message_from -- name of person from whom the gift is from :gift_message_from-礼物来自的人的名字

:gift_message_message -- their message :gift_message_message-他们的信息

:gift_recipient_email -- an email will be sent out to the recipient notifying them that they will be receiving a gift. :gift_recipient_email-将会向收件人发送一封电子邮件,通知他们他们将收到礼物。 This would use a regex expression and html5 to make sure it is a properly formatted email address. 这将使用正则表达式和html5来确保它是格式正确的电子邮件地址。

I was thinking would create my own validation method 我当时想创建自己的验证方法

  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

and validating it 并验证它

validate :order_has_gift_message_field

So if the user starts entering any of these fields, the other fields would also need to be filled out. 因此,如果用户开始输入这些字段中的任何一个,其他字段也需要填写。 but if they do not enter any information, the validations would not be present. 但是如果他们不输入任何信息,则不会显示验证信息。 Has anyone done something similar to this? 有人做过类似的事情吗? Any suggestions would be greatly appreciated. 任何建议将不胜感激。

Have a look at the Rails guide's custom validations . 看一下Rails指南的自定义验证

There is an example there for making a custom validations method like you suggest. 有一个示例可以像您建议的那样制作自定义验证方法。

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