Skip to content

feat: new rule proposal: no-invalid-entity-351 #371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"treegrid",
"contentinfo",
"smashingmagazine",
"contenteditable"
"contenteditable",
"nbsb"
]
}
1 change: 1 addition & 0 deletions docs/rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
| [no-duplicate-class](rules/no-duplicate-class) | Disallow to use duplicate class | 🔧 |
| [no-duplicate-id](rules/no-duplicate-id) | Disallow to use duplicate id | ⭐ |
| [no-inline-styles](rules/no-inline-styles) | Disallow using inline style | |
| [no-invalid-entity](rules/no-invalid-entity) | Disallows the use of invalid HTML entities | |
| [no-nested-interactive](rules/no-nested-interactive) | Disallows nested interactive elements | |
| [no-obsolete-tags](rules/no-obsolete-tags) | Disallow to use obsolete elements in HTML5 | ⭐ |
| [no-restricted-attr-values](rules/no-restricted-attr-values) | Disallow specified attributes | |
Expand Down
43 changes: 43 additions & 0 deletions docs/rules/no-invalid-entity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# no-invalid-entity

Disallow use of invalid HTML entities.

## Rule Details

This rule disallows the use of invalid HTML entities in your markup. HTML entities are special codes used to represent characters with specific meanings in HTML, such as `<` (`<`) or `&` (`&`). Invalid entities—such as typos, undefined entities, or malformed numeric references—can be silently ignored by browsers, leading to rendering issues or confusion.

The rule validates both named entities (e.g., ` `) and numeric entities (e.g., ` ` for decimal or ` ` for hexadecimal) against a list of valid entities defined in `entities.json`. An entity is considered invalid if:

- It is a named entity not found in `entities.json` (e.g., `&nbsb;` or `&unknown;`).
- It is a numeric entity with an invalid format (e.g., `&#zzzz;`).
- It is a numeric entity outside the valid Unicode range (0 to 0x10FFFF, e.g., `�`).

## How to use

```js,.eslintrc.js
module.exports = {
rules: {
"@html-eslint/no-invalid-entity": "error",
},
};
```

### Examples

#### Incorrect Code

```html
<p>&nbsb;</p> <!-- typo -->
<p>&unknown;</p> <!-- undefined entity -->
<p>&#zzzz;</p> <!-- invalid numeric reference -->
```

#### Correct Code

```html
<p>&lt; &gt; &amp; &nbsp; &#160; &#xA0;</p>
```

## When Not To Use It

Disable this rule if you are intentionally using invalid entities for specific purposes, such as testing or non-standard rendering. Be aware that invalid entities may not render consistently across different browsers.
2,299 changes: 2,299 additions & 0 deletions packages/eslint-plugin/lib/data/entities.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions packages/eslint-plugin/lib/rules/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const requireExplicitSize = require("./require-explicit-size");
const useBaseLine = require("./use-baseline");
const noDuplicateClass = require("./no-duplicate-class");
const noEmptyHeadings = require("./no-empty-headings");
const noInvalidEntity = require("./no-invalid-entity");
// import new rule here ↑
// DO NOT REMOVE THIS COMMENT

Expand Down Expand Up @@ -104,6 +105,7 @@ const rules = {
"use-baseline": useBaseLine,
"no-duplicate-class": noDuplicateClass,
"no-empty-headings": noEmptyHeadings,
"no-invalid-entity": noInvalidEntity,
// export new rule here ↑
// DO NOT REMOVE THIS COMMENT
};
Expand Down
108 changes: 108 additions & 0 deletions packages/eslint-plugin/lib/rules/no-invalid-entity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**
* @typedef { import("../types").RuleModule<[]> } RuleModule
* @typedef { import("../types").SuggestionReportDescriptor } SuggestionReportDescriptor
* @typedef { import("@html-eslint/types").Text} Text
*/

// Define the type for entities.json
/**
* @typedef {Object} EntityData
* @property {number[]} codepoints
* @property {string} characters
*/

/** @type {{ [key: string]: EntityData }} */
const entities = require("../data/entities.json");

const { RULE_CATEGORY } = require("../constants");
const { createVisitors } = require("./utils/visitors");
const { getRuleUrl } = require("./utils/rule");

const MESSAGE_IDS = {
INVALID_ENTITY: "invalidEntity",
};

/**
* @type {RuleModule}
*/
module.exports = {
meta: {
type: "code",
docs: {
description: "Disallows the use of invalid HTML entities",
category: RULE_CATEGORY.BEST_PRACTICE,
recommended: false,
url: getRuleUrl("no-invalid-entity"),
},
fixable: null,
hasSuggestions: false,
schema: [],
messages: {
[MESSAGE_IDS.INVALID_ENTITY]: "Invalid HTML entity '{{entity}}' used.",
},
},

create(context) {
/**
* @param {Text} node
*/
function check(node) {
const text = node.value;

// Regular expression to match named and numeric entities
const entityRegex = /&([a-zA-Z]+|#[0-9]+|#x[0-9a-fA-F]+|[#][^;]+);/g;
let match;

while ((match = entityRegex.exec(text)) !== null) {
const entity = match[0];
const entityName = match[1];

// Check named entities
if (!entityName.startsWith("#")) {
const fullEntity = `&${entityName};`;
if (!Object.prototype.hasOwnProperty.call(entities, fullEntity)) {
context.report({
node,
messageId: MESSAGE_IDS.INVALID_ENTITY,
data: { entity },
});
}
}
// Check numeric entities
else {
const isHex = entityName[1] === "x";
const numStr = isHex ? entityName.slice(2) : entityName.slice(1);
const num = isHex ? parseInt(numStr, 16) : parseInt(numStr, 10);

// If the number is not a valid integer, report an error
if (isNaN(num)) {
context.report({
node,
messageId: MESSAGE_IDS.INVALID_ENTITY,
data: { entity },
});
continue;
}

// Check if the numeric entity is valid (exists in entities.json or within valid Unicode range)
const entityKey = Object.keys(entities).find((key) => {
const codepoints = entities[key].codepoints;
return codepoints.length === 1 && codepoints[0] === num;
});

if (!entityKey && (num < 0 || num > 0x10ffff)) {
context.report({
node,
messageId: MESSAGE_IDS.INVALID_ENTITY,
data: { entity },
});
}
}
}
}

return createVisitors(context, {
Text: check,
});
},
};
40 changes: 40 additions & 0 deletions packages/eslint-plugin/tests/rules/no-invalid-entity.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const createRuleTester = require("../rule-tester");
const rule = require("../../lib/rules/no-invalid-entity");

const ruleTester = createRuleTester();
const templateRuleTester = createRuleTester("espree");

ruleTester.run("no-invalid-entity", rule, {
valid: [
{ code: "<p>&lt; &gt; &amp; &nbsp;</p>" },
{ code: "<p>&#xD55C;</p>" },
],
invalid: [
{
code: "<p>&nbsb;</p>", // Typo in entity name
errors: [{ message: "Invalid HTML entity '&nbsb;' used." }],
},
{
code: "<p>&unknown;</p>", // Undefined entity
errors: [{ message: "Invalid HTML entity '&unknown;' used." }],
},
{
code: "<p>&#zzzz;</p>", // Invalid numeric entity
errors: [{ message: "Invalid HTML entity '&#zzzz;' used." }],
},
{
code: "<p>&#x110000;</p>",
errors: [{ message: "Invalid HTML entity '&#x110000;' used." }],
},
],
});

templateRuleTester.run("[template] no-invalid-entity", rule, {
valid: [{ code: `html\`<p>&lt; &gt; &amp; &nbsp;</p>\`` }],
invalid: [
{
code: "html`<p>&nbsb;</p>`",
errors: [{ message: "Invalid HTML entity '&nbsb;' used." }],
},
],
});