Skip to content

Commit 62ab75e

Browse files
authored
add a11y-label-has-associated-control check (#5074)
1 parent f0d586f commit 62ab75e

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

src/compiler/compile/nodes/Element.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,17 @@ const a11y_no_onchange = new Set([
6161
'option'
6262
]);
6363

64+
const a11y_labelable = new Set([
65+
"button",
66+
"input",
67+
"keygen",
68+
"meter",
69+
"output",
70+
"progress",
71+
"select",
72+
"textarea"
73+
]);
74+
6475
const invisible_elements = new Set(['meta', 'html', 'script', 'style']);
6576

6677
const valid_modifiers = new Set([
@@ -507,6 +518,16 @@ export default class Element extends Node {
507518
}
508519
}
509520

521+
if (this.name === 'label') {
522+
const has_input_child = this.children.some(i => (i instanceof Element && a11y_labelable.has(i.name) ));
523+
if (!attribute_map.has('for') && !has_input_child) {
524+
component.warn(this, {
525+
code: `a11y-label-has-associated-control`,
526+
message: `A11y: A form label must be associated with a control.`
527+
});
528+
}
529+
}
530+
510531
if (a11y_no_onchange.has(this.name)) {
511532
if (handlers_map.has('change') && !handlers_map.has('blur')) {
512533
component.warn(this, {
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<label>A</label>
2+
<label for="id">B</label>
3+
4+
<label>C <input type="text" /></label>
5+
<label>D <button>D</button></label>
6+
<label>E <span></span></label>
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
[
2+
{
3+
"code": "a11y-label-has-associated-control",
4+
"end": {
5+
"character": 16,
6+
"column": 16,
7+
"line": 1
8+
},
9+
"message": "A11y: A form label must be associated with a control.",
10+
"pos": 0,
11+
"start": {
12+
"character": 0,
13+
"column": 0,
14+
"line": 1
15+
}
16+
},
17+
{
18+
"code": "a11y-label-has-associated-control",
19+
"end": {
20+
"character": 149,
21+
"column": 30,
22+
"line": 6
23+
},
24+
"message": "A11y: A form label must be associated with a control.",
25+
"pos": 119,
26+
"start": {
27+
"character": 119,
28+
"column": 0,
29+
"line": 6
30+
}
31+
}
32+
]

0 commit comments

Comments
 (0)