Skip to content

Commit 2c0e476

Browse files
committed
New rule to flag invalid aria-label format
1 parent 3d38ceb commit 2c0e476

2 files changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
const {getProp, getPropValue} = require('jsx-ast-utils')
2+
3+
module.exports = {
4+
meta: {
5+
docs: {
6+
description: '[aria-label] text should be formatted as you would visible text, in a human-readable format.',
7+
url: require('../url')(module),
8+
},
9+
schema: [],
10+
},
11+
12+
create(context) {
13+
return {
14+
JSXOpeningElement: node => {
15+
const prop = getProp(node.attributes, 'aria-label')
16+
if(!prop) return
17+
18+
const propValue = prop.value;
19+
if (propValue.type !== 'Literal') return
20+
21+
const ariaLabel = propValue.value
22+
if (ariaLabel.match(/^[a-z]+[a-z\-\.\s]*$/)) {
23+
context.report({
24+
node,
25+
message: '[aria-label] text should be formatted the same as you would visible text. Use sentence case and make sure you are not using hyphens.',
26+
})
27+
}
28+
},
29+
}
30+
},
31+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
const rule = require('../lib/rules/a11y-aria-label-is-readable')
2+
const RuleTester = require('eslint').RuleTester
3+
4+
const ruleTester = new RuleTester({
5+
parserOptions: {
6+
ecmaVersion: 'latest',
7+
sourceType: 'module',
8+
ecmaFeatures: {
9+
jsx: true,
10+
},
11+
},
12+
})
13+
14+
const errorMessage =
15+
'[aria-label] text should be formatted the same as you would visible text.'
16+
17+
ruleTester.run('a11y-aria-label-is-readable', rule, {
18+
valid: [
19+
{code: "<a aria-labelledby='someId' href='#'>Read more</a>;"},
20+
{code: "<a aria-label={someName} href='#'>Read more</a>;"},
21+
{code: "<a aria-label='This is a label'></a>;"},
22+
{
23+
code: '<Link as="button" href="#">Read more</Link>',
24+
},
25+
],
26+
invalid: [
27+
{code: "<a aria-label='close modal'></a>;", errors: [{message: errorMessage}]},
28+
{code: "<a aria-label='submit'></a>;", errors: [{message: errorMessage}]},
29+
{code: "<a aria-label='this-is-not-an-id'></a>;", errors: [{message: errorMessage}]},
30+
],
31+
})

0 commit comments

Comments
 (0)