I'm creating a custom validation for my HTML form to change the maxlength
attribute behavior from blocking the input above limit to non-blocking, so users are allowed to enter more characters than the specified limit but will see an error instead. However, I'm having trouble getting it to work with disabled fields.
I've read in the specification (source) that:
If an element is disabled, it is barred from constraint validation.
This seems to hold true for inputs with the required
attribute in that the validity.valueMissing
is false
when the field is disabled
and has no value. But when the field has maxlength
attribute set, the validity.tooLong
is true
when the field is disabled
and has a value longer than maxlength
.
In the below example, when I enter more than 10 characters in the input field, click the "Toggle disabled" button to disable the field and then click the "Report validity" button, the error is shown when I would expect it not to show (checked on Chrome and Firefox).
const input = document.getElementById("input");
const errMsg = document.getElementById("err-msg");
const btnToggle = document.getElementById("btn-toggle");
const btnReport = document.getElementById("btn-report");
btnToggle.addEventListener("click", () => {
input.disabled = !input.disabled;
});
btnReport.addEventListener("click", () => {
input.maxLength = "10";
if(input.validity.tooLong) {
input.style.border = "red solid 1px";
errMsg.style.display = "block";
} else {
input.style.border = "revert";
errMsg.style.display = "none";
}
input.removeAttribute("maxlength");
});
<input id="input" type="text" value="">
<div id="err-msg" style="color: red; display: none;">Input should have at most 10 characters.</div>
<div>
<button id="btn-toggle">Toggle disabled</button>
<button id="btn-report">Report validity</button>
</div>
Am I missing something from the specification? How can I leverage the built-in validation mechanism to:
Even when an element's constraint validation is disabled, the .validity
properties are still set. From 4.10.20.1 Definitions
Note
An element can still suffer from these states even when the element is disabled; thus these states can be represented in the DOM even if validating the form during submission wouldn't indicate a problem to the user.