svelandiag
svelandiag

Reputation: 4320

Skip validation on certain field when a condition is met

Hi Im having troubble trying to do the following.

Im making a checkout page, I have a form like this

  <%= form_for([@ofert, @order], builder: FoundationFormBuilder) do |f| %>

    <%= f.fields_for :invoice_address do |builder| %>
        <%= render partial: 'invoice_address_fields', locals: { f: builder } %>
    <% end %>

    <%= f.check_box :invoice_equals_shipping, checked: true, label: 'My Invoice address is the same Shipping address' %>

    <%= f.fields_for :shipping_address do |builder| %>
      <%= render partial: 'shipping_address_fields', locals: { f: builder } %>
    <% end %>

    .....
    <% end %>

well the checkbox "My Invoice address is the same Shipping address" is checked by de fault, the "shipping_address" field is hidden by default using jquery.

Well both fields are empty at the beginning, So the user usually will fill the invoice_address field and will leave the checkbox "My Invoice address is the same Shipping address" checked, well the problem is that the hidden field "shipping_address" is validated "field cannot be blank"

How can I validate that when checkbox is checked do not validate the field?

Upvotes: 1

Views: 232

Answers (1)

spickermann
spickermann

Reputation: 106802

You can add a condition to validates in your model. Something like:

validates :shipping_address, presence: true, unless: :invoice_equals_shipping?

Upvotes: 3

Related Questions