It looks like when an input element is initially loaded, its validity is not evaluated right away. For example, if my HTML looks like this...
<input type="text" value="ABC" minlength="5">
In JavaScript it appears that the input is valid and not too short, despite the value attribute being set to a length less than 5. For example:
const input = document.querySelector("input");
console.log(input.validity.valid); // true
console.log(input.validity.tooShort); // false
Only when the user makes a change in the input can we get a true reckoning of the input's validity.
Is there any way to force the input to evaluate its actual validity on load, even if the user has not yet touched the input?
See example: https://jsfiddle.net/t5afujkn/3/
I guess the reason is your default value is not checked from <input> directly at load as it probably does not trigger a check for the default values.
You can add another check condition in your js as below:
{
const displayObj = {
valid: input.validity.valid,
tooShort: input.validity.tooShort
};
if (input.value.length < 5) {
displayObj.valid = false;
displayObj.tooShort = true;
document.querySelector("p").textContent = JSON.stringify(displayObj);
}
}
or maybe you can also try to put the if condition somewhere outside the button call.
Also I did an update in jsfiddle, not sure if you can see it: https://jsfiddle.net/2Lhp96ct/6/