Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Input validity not checked when value is changed by Javascript

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?

like image 883
Coderer Avatar asked Mar 06 '23 02:03

Coderer


1 Answers

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.

like image 184
Coderer Avatar answered Apr 30 '23 05:04

Coderer