HTML: RSPEC-1097 flags inputs wrapped in label elements

Based on RSPEC-1097 SonarLint in VS Code issues error messages for the input elements in the following code:

<form>
  <fieldset>
    <legend>Gender</legend>
    <p><label><input name="gender" type="radio" value="fe"> Feminine</label></p>
    <p><label><input name="gender" type="radio" value="ma"> Masculine</label></p>
    <p><label><input name="gender" type="radio" value="nb"> Non-binary</label></p>
  </fieldset>
  <p><button type="submit">Submit</button> <button type="reset">Reset</button></p>
</form>

The most common method of connecting an input with its label consists in using for and id attributes as in the following example:

<input name="gender" type="radio" value="fe" id="gender-fe"> <label for="gender-fe"> Feminine</label>

However, the method in the first code example is both valid and accessible. SonarLint should not produce the following error message:

Provide an aria-label [aria-label=“”]

This error message is misleading for two reasons:

  1. The code is valid and accessible, as mentioned above, so nothing needs to be done.
  2. Adding an aria-label attribute when a native element (in this case the label element) can serve the same purpose is not a good practice. The error message sends developers in the wrong direction.

For an example of a label element that wraps around the input, see also WebAIM’s article Creating Accessible Forms, which says:

You can also create the association by placing the label text and the input within the <label> element (and not using for and id).

<label>Name: <input type="text" autocomplete="name"></label>

1 Like

Hi Christophe,

Thanks for bringing this up. I agree this is a false positive and Sonar should be able to know input inside label is audible and accessible already.

I created an issue to track this:
https://sonarsource.atlassian.net/issues/SONARHTML-222

Kind regards,

1 Like