简体   繁体   中英

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

:gift_message_to -- enter information about who the gift is for

:gift_message_from -- name of person from whom the gift is from

:gift_message_message -- their message

:gift_recipient_email -- an email will be sent out to the recipient notifying them that they will be receiving a gift. This would use a regex expression and html5 to make sure it is a properly formatted email address.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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