required-attr
Warns if specified attributes or required attribute on specs are not appeared on an element.
This rule refer HTML Living Standard based MDN Web docs. It has settings in @markuplint/html-spec.
๐ Example of incorrect code for this rule
<img />
<!-- "required-attr": "alt" -->
<img src="/path/to/image.png" />
๐ Example of correct code for this rule
<img src="/path/to/image.png" />
<!-- "required-attr": "alt" -->
<img src="/path/to/image.png" alt="alternative text" />
This rule doesn't evaluate the element that has the spread attribute. In the below code, it doesn't evaluate whether the img element includes the src attribute. Because markuplint can't know whether the spread attribute includes the src property.
const Component = (props) => {
return <img {...props}>;
}
Interfaceโ
{
"required-attr": string | (string | Attr)[]
}
type Attr = {
name: string;
value?: string | string[];
};
Optionsโ
{
"required-attr": {
"options": {
"ignoreAttrs"?: string[]
}
}
}
| Property | Type | Default Value | Description |
|---|---|---|---|
ignoreAttrs | string[] | undefined | Attribute names to exclude from required-attribute checks. Use this when you want to ignore specific required attributes without disabling the entire rule. |
Default Severityโ
error
Configuration Exampleโ
{
"rules": {
"required-attr": "alt"
}
}
{
"rules": {
"required-attr": ["alt", "src"]
}
}
{
"rules": {
"required-attr": [
"alt",
{
"name": "src",
"value": "/^\\/|^https:\\/\\//i"
}
]
}
}
Since we ordinary want to configure required attributes for each element type, required-attr rule should be configured in the nodeRules option.
Example configuration that alt attribute must be required on <img> element:
{
"rules": {
"required-attr": true
},
"nodeRules": [
{
"selector": "img",
"rules": {
"required-attr": "alt"
}
}
]
}
ignoreAttrsโ
You can use the ignoreAttrs option to exclude specific attributes from required-attribute checks. This is useful when you want to keep the rule enabled but ignore certain attributes that are handled by a framework or are intentionally omitted.
{
"nodeRules": [
{
"selector": "img",
"rules": {
"required-attr": {
"options": {
"ignoreAttrs": ["src", "srcset"]
}
}
}
}
]
}