1

I need a way for my form to not be sent if the user didn't bother to select any radio buttons.

I'd like to to that within the view and the controller, not in the model (the data shouldn't even be sent)

<%= form_tag("/bookings/new", method: "get") do %>
  <% @flights.each do |flight| %>
    <%= radio_button_tag :flight_id, flight.id %>
  <% end %>
  <%= submit_tag "book now" %>
<% end %>

edit, to clarify
normally I'd do
<%= f.text_field :name, required: true %>
but, as I have many radio buttons and I only need one for the form to work, I don't know how to implement it

Salomanuel
  • 897
  • 10
  • 22
  • What do you mean "the data shouldn't even be sent"? If you don't want the form to be submitted (i.e., no request/response cycle between the front end and the server), then you probably need to use javascript on the front end. – jvillian Oct 13 '17 at 13:48
  • You mean you want validation in front end and not in model? – krishnar Oct 13 '17 at 13:55
  • 1
    This question is more javascript-related than rails-related. Cf: https://stackoverflow.com/questions/1423777/how-can-i-check-whether-a-radio-button-is-selected-with-javascript – ArnoHolo Oct 13 '17 at 14:01
  • 1
    `<%= f.text_field :name, required: true %>` This still works perfectly for radio buttons, and it's okay if it ends up on all radio items. The form will still only require one input. (Adding this as an answer as well, for visibility) – Bek Aug 08 '22 at 21:42

2 Answers2

2

<%= f.text_field :name, required: true %>

This still works perfectly for radio buttons, and it's okay if it ends up on all radio items. The form will still only require one input.

I just tested it on my Rails 6 app.

Bek
  • 2,206
  • 20
  • 35
0

You can set validation in the model to see the presence of checkbox if javascript is disabled. This is a more robust method.

validates :flight_id, :acceptance => true

Docs here - http://guides.rubyonrails.org/active_record_validations.html#acceptance

Edit

function validateCheckBox() {
    var x = document.getElementById("flight_id").checked;
    if(!x) {alert("Not checked")}        
}

<%= submit_tag "book now" , :onclick => "validateCheckBox();" %>
arjun
  • 1,594
  • 16
  • 33
  • As I wrote in the second line of my post, I'd like to to that within the view and the controller, not in the model – Salomanuel Oct 13 '17 at 14:07
  • 2
    When you talk about views and controller, that immediately translates to a front-end problem. Use javascript. See edit. – arjun Oct 13 '17 at 14:21
  • You absolutely do not need javascript. The `required: true` param in the form helper adds the HTML5 required attribute. The answer provided by Bek is correct in that you would just add the same `required: true` to both radio button fields. – daybreaker May 16 '23 at 17:52