This example shows how we use the aria-errormessage
to set the error message for reporting entry of an invalid email address, and demonstrates how we can get and set the message using ariaErrorMessageElements
.
First we define an HTML email input, setting its aria-errormessage
attribute to reference an element with the id
of err1
. We then define a <span>
element that has this id, and which contains an error message.
<p>
<label for="email">Email address:</label>
<input type="email" name="email" id="email" aria-errormessage="err1" />
<span id="err1" class="errormessage">Error: Enter a valid email address</span>
</p>
CSS
We create some styles to hide the error message by default, but make it visible and styled as an error when aria-invalid
is set on the element.
.errormessage {
visibility: hidden;
}
[aria-invalid="true"] {
outline: 2px solid red;
}
[aria-invalid="true"] ~ .errormessage {
visibility: visible;
}
JavaScript
We then check for input, and set ariaInvalid
to true
or false
based on the typeMismatch
constraint violation. ariaInvalid
is in turn reflected in the aria-invalid
attribute, which hides and displays the error as needed.
const email = document.querySelector("#email");
email.addEventListener("input", (event) => {
if (email.validity.typeMismatch) {
email.ariaInvalid = true;
} else {
email.ariaInvalid = false;
}
});
#log {
height: 70px;
overflow: scroll;
padding: 0.5rem;
border: 1px solid black;
}
const logElement = document.querySelector("#log");
function log(text) {
logElement.innerText = `${logElement.innerText}${text}\n`;
logElement.scrollTop = logElement.scrollHeight;
}
We then log the value of the aria-errormessage
attribute, the ariaErrorMessageElements
and the inner text of the ariaErrorMessageElements
log(`aria-errormessage: ${email.getAttribute("aria-errormessage")}`);
// Feature test for ariaErrorMessageElements
if ("ariaErrorMessageElements" in Element.prototype) {
// Get ariaErrorMessageElements
const propElements = email.ariaErrorMessageElements;
log(`ariaErrorMessageElements: ${propElements}`);
// Accessible text from element inner text
const text = propElements.map((e) => e.textContent.trim).join(" ");
log(`Error message details: ${text.trim()}`);
} else {
log("element.ariaErrorMessageElements: not supported by browser");
}
Result
As you enter an email address, the error text will be displayed until the email address is valid. Note that the log shows the error message reference read from the attribute, the element from ariaErrorMessageElements
, and the inner text of the element, which is its error message.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4