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:
- The code is valid and accessible, as mentioned above, so nothing needs to be done.
- Adding an
aria-label
attribute when a native element (in this case thelabel
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 usingfor
andid
).
<label>Name: <input type="text" autocomplete="name"></label>