need to be able to create accessible input error labels

Author: ajfarkasCreated Sep 5, 2024Updated Sep 5, 2024

Precheck

[x] Do not use the issues tracker for help or support, try Stack Overflow. [x] For bugs, do a quick search and make sure the bug has not yet been reported [x] Finally, be nice and have fun!

Environment

  • Ruby 3.3.1
  • Rails 7.1.3
  • Simple Form 5.3.0

Background

I'm attempting to make a form that validates errors server-side on submit. The form needs to programmatically associate the error text with the appropriate input field, preferably by amending the label to include the error in a span that is hidden from sight (there is separate error text that is visually but not programmatically associated with the input.
Because the validations are on submit, using role: 'alert' does not do anything because this creates a new accTree, and alerts only read contents on content change, not creation.

Current behavior

While this is currently possible, it's via a fairly complex workaround that requires me to explicitly set this on each input on my lengthy form.

I would like to accomplish this via SimpleForm.setup. The current behavior is that I can only set up a label (with appropriate for attribute) with the form's :label text. I could do something like:

ruby
 b.wrapper tag: 'label', class: 'my-label' do |c|
  c.use :label_text
  c.use :error, class: 'sr-only'
end

but I cannot associate this label with the input.

Will be even more helpful if you provide a sample application or a test case that reproduces the error.

Expected behavior

The short version is I'd like to be able to easily create a form that programmatically announces errors to screen readers, even on page refresh (as long as errors are present).

This could be accomplished a number of ways.

I would like a way to either add an input error within a label, or to associate a wrapper with another element with a for attribute. Maybe something like:

ruby
b.wrapper tag: :label, for: :input_id do |c|
  c.use :label_text
  c.use :error, class: 'sr-only'
end

Notes

I really appreciate this project. I'm using this on a major product, and the learning curve has been reasonable while the gem has really allow my team to reduce their code (and therefore reduce errors). So, thank you!