I have a text input with minlength
defined. When a user enters text, the input's validity
state is updated immediately. If I alter the value in code, the validity state reset to show as valid -- even with a constraint violated, validity.valid
is true.
const input = document.getElementById("input");
const label = document.getElementById("label");
document.getElementById("rightButton").addEventListener("click", evt => {
input.value = "ABCDE";
});
document.getElementById("wrongButton").addEventListener("click", evt => {
input.value = "AB";
});
setInterval(() => label.innerHTML = input.validity.valid, 250);
<input type="text" id="input" minlength="4">
<span id="label"></span>
<hr/>
<button id="rightButton">Make It Right</button>
<button id="wrongButton">Make It Wrong</button>
Why doesn't automatic validity checking run when I assign to input.value
? Is this documented somewhere? Is there a method I can call to trigger the browser's internal validation process, rather than having to do my own checks and call setCustomValidity
?
Using pattern
is a reasonable approach to solving my problem, and all credit to Sujil for prompting me to run down exactly what's going on here. I just wanted to clarify for any future readers with this issue.
From the spec for minlength
(emphasis mine):
If an element has a minimum allowed value length, its dirty value flag is true, its value was last changed by a user edit (as opposed to a change made by a script), its value is not the empty string, and the code-unit length of the element’s value is less than the element’s minimum allowed value length, then the element is suffering from being too short.
This language ("last changed by a user edit") is also in the spec for maxlength, but not for any other constraints. That's why there is no method to "force validation", because all constraints are being applied all the time, except these two. I'm not sure why, but it's very clear and universally implemented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With