Improve accessibility with [aria-required] in SimpleForm

Posted . Visible to the public.

SimpleForm comes with an option browser_validations which could be used to give fields that have a presence validation the HTML required Show archive.org snapshot attribute. We usually turn it off, and only mark required fields with an asterisk (*) next to its label. Blind users probably only discover the validation issue after submitting the form due to the now displayed error messages.

A compromise with better accessibility is to add the aria-required Show archive.org snapshot attribute in this case. This allows screen readers to announce fields as required before the form is submitted.

  1. Define a SimpleForm component:
module SimpleForm
  module Components
    module AriaRequired
      def aria_required(_wrapper_options)
        if required_field?
          input_html_options['aria-required'] = 'true'
        end
        nil
      end
    end
  end
end

SimpleForm::Inputs::Base.include(SimpleForm::Components::AriaRequired)
  1. Change all your wrappers to use it:
SimpleForm.setup do |config|
  config.browser_validations = false
  
  config.wrappers :default, error_class: :field_with_errors do |b|
    b.use :aria_required
  end
end
Michael Leimstädtner
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Michael Leimstädtner to makandra dev (2025-08-25 14:03)