【问题标题】:Rails 5 simple_form mark radio button as required & prevent form submit if not filledRails 5 simple_form 将单选按钮标记为必需,如果未填写则阻止提交表单
【发布时间】:2020-01-30 23:02:20
【问题描述】:

我想根据需要在我的表单中标记一个单选按钮字段,这样如果用户单击提交(不选择单选按钮选项),他会收到一个错误,即该字段是必需的,就像普通输入字段发生的情况一样(当有选项required: true如图所示)

例如:(这很好用)

= f.input :value, required: true

但这不起作用:

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

我正在使用 Rails 5.2、simple_form 和 jQuery,虽然我确信这个用例面临许多开发人员,但我找不到相关的问题/答案,除了 javascript hacks(我更喜欢避免并更喜欢使用 Rails 或 simple_form 方式强制执行此前端验证)

【问题讨论】:

    标签: javascript jquery ruby-on-rails simple-form


    【解决方案1】:

    检查方法的签名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)
    

    您有一个 options 哈希,然后是一个 html_options 哈希。您对该方法的调用是将required: true 设置为选项,我认为您需要将其设置为html_option。在:last 和required: true 之间添加一个空的{}。

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

    【讨论】:

    • 这正是缺少的!非常感谢!
    猜你喜欢
    • 2018-11-20
    • 2023-04-01
    • 2017-10-10
    • 2016-03-14
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多