Devildude4427
Devildude4427

Reputation: 1088

HTML input checkValidity() always returns true even with minlength violations

Pretty simple set up:

const input = window.document.getElementById('Input');
input.value = "foobar"
console.log(input.checkValidity());
<input id="Input" type="text" minlength="8" required />

The following returns true when it should be false. See https://jsbin.com/huqowesewu/edit?html,output

Why in the world is this? The input has a length of 6, which is less than 8, ergo, it should be invalid. But it's not. Is this attribute broken? Or is checkValidity() broken? I'm baffled to say the least.

Upvotes: 15

Views: 3411

Answers (2)

user15525969
user15525969

Reputation: 1

This is a better way to get false.

function myfunction() {
  var iny = document.getElementById("Input");
  document.getElementById("demo").innerHTML = iny.checkValidity();
}
<input type="text" minlength="8" id="Input" required />
<button onclick="myfunction()">TRY</button>
<p id="demo"></p>

Upvotes: -1

Theraot
Theraot

Reputation: 40315

This should work. As per WHATWG it should work. As per caniuse.com it should work.

However, it appears to only work when the value was edited by the user, not set from JavaScript. I did not find anything on WHATWG or MDN regarding that behavior (perhaps it is there, and I don't know where to look).

It is documented on WHATWG. Both minlength and maxlength require user interaction. To be more precise, when the user modifies the input value a "dirty value flag" is set, which is taken into account in the validation. See Limiting user input length: the maxlength attribute:

Constraint validation: 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 length of the element's API value is less than the element's minimum allowed value length, then the element is suffering from being too short.


Things I tested but do not make it work: Listening to the "invalid" event. Triggering an "input" event. Removing focus from the input with blur() before checking. Checking from queueMicrotask(function). Checking from requestAnimationFrame(function). Checking from double requestAnimationFrame(function). Checking with a valid value and then checking with an invalid value. Setting either a valid or an non-empty invalid default value via HTML attribute. Setting the value with setAttribute from JavaScript. Setting defaultValue.

I tested on Chromium Edge and Firefox.

I also found the question How can I trigger the minlength validation when field is set programmatically? which provided no solution.


Anyway, you can use pattern to mimic this validation constraint. And yes, that one will trigger from JavaScript correctly, as most validation constraints do. See https://stackoverflow.com/a/10294291/402022

Upvotes: 16

Related Questions