Search code examples
javascriptjqueryruby-on-railssimple-form

Rails 5 simple_form mark radio button as required & prevent form submit if not filled


I want to mark a radio button field in my form as required, so that if the user click submit (without choosing a radio button option) he will get an error that this field is required just like what happens with normal input fields (when having the option required: true as shown in the picture)

For example: (this works well)

= f.input :value, required: true

enter image description here

But this doesn't work:

= f.collection_radio_buttons :some_symbol, [[true, t('yes')], [false, t('no')]], :first, :last, required: true

I am using Rails 5.2, simple_form & jQuery and although I am sure this use case faced many developers I can't find a relevant question/answer except javascript hacks (which I prefer to avoid & prefer to use Rails or simple_form way to enforce this frontend validation)


Solution

  • Check the method's signature https://apidock.com/rails/v6.0.0/ActionView/Helpers/FormOptionsHelper/collection_radio_buttons

    collection_radio_buttons(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
    

    You have an options hash and then an html_options hash. Your call to the method is setting required: true as an option and I think you need to set it as an html_option. Add an empty {} between :last and required: true.

    = f.collection_radio_buttons :some_symbol, [[true, t('yes')], [false, t('no')]], :first, :last, {}, required: true