Reputation: 864
I have a checkbox to display delivery address if an item has the menu_type = 'Lunch'
, this part of the form is hidden with jQuery until the checkbox is checked but how do I validate these fields if the checkbox is checked?
<%= simple_form_for @order do |f| %>
<div class="row">
<div class="large-4 columns">
<h4>Customer Details</h4>
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :email %>
<%= f.input :phone_number %>
</div>
<div class="large-4 columns">
<h4>Billing Address</h4>
<%= f.input :billing_line_1, :label => 'Billing Address Line 1' %>
<%= f.input :billing_line_2, :label => 'Billing Address Line 2' %>
<%= f.input :billing_line_3, :label => 'Billing Address Line 3' %>
<%= f.input :billing_postcode, :label => 'Billing Postcode' %>
<% if @order.order_items.first.item.menu_type == 'Lunch' %>
<%= f.input :lunch_delivery, :label => 'Lunch Time Delivery?' %>
<% end %>
<div id="deliveryAddress">
<h4>Delivery Address</h4>
<%= f.input :delivery_line_1, :label => 'Delivery Address Line 1' %>
<%= f.input :delivery_line_2, :label => 'Delivery Address Line 2' %>
<%= f.input :delivery_line_3, :label => 'Delivery Address Line 3' %>
<%= f.input :delivery_postcode, :label => 'Delivery Postcode' %>
</div>
</div>
<div class="large-4 columns">
<%= f.button :submit, "Place order" %>
</div>
</div>
<% end %>
class Order < ActiveRecord::Base
attr_accessible :billing_line_1, :billing_line_2, :billing_line_3, :billing_postcode, :delivery_line_1, :delivery_line_2, :delivery_line_3, :delivery_postcode, :phone_number, :email, :first_name, :last_name, :lunch_delivery
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, presence: true
validates :billing_line_1, presence: true
validates :billing_postcode, presence: true
validates :phone_number, presence: true
end
$("#order_lunch_delivery").click ->
if $(this).is(":checked")
$("#deliveryAddress").show()
else
$("#deliveryAddress").hide()
return
Upvotes: 0
Views: 126
Reputation: 9294
It sounds like you're looking for conditional validation. It would look like
validates :delivery_line_1, presence: true, if: :lunch_delivery
Upvotes: 1