2

Let me show some examples so you understand the problem clearly.

✔️ Exemple 1 : working as expected

Consider an input <input required /> and some css to visualize his validity.

console.log( document.querySelector('input').checkValidity() )
input:invalid { background: pink; }
<input required />

If we check it's validity state via Javascript inputEl.checkValidity() we get a false, looking further in inputEl.validity shows { valueMissing: true, typeMismatch: false, …}

Ok everything is logic for now.

✔️ Exemple 2 : working as expected

Now if we add a value to the input, validation should be fine :

console.log( document.querySelector('input').checkValidity() )
input:invalid { background: pink; }
<input required value="John Cena" />

If we check it's validity state via Javascript inputEl.checkValidity() we get a true.

Make sense.

❌ Exemple 3 : not working as expected

Let's add maxlength="5" :

console.log( document.querySelector('input').checkValidity() )
input:invalid { background: pink; }
<input required value="John Cena" maxlength="5" />

Why is the field not invalid initially ?

If we check it's validity state via Javascript inputEl.checkValidity() we get a true ... ?

Also if we edit this input, then the validation will be updated and the field will be marked as invalid.

Here is the full exemple : https://codepen.io/Shuunen/pen/XWaqpVo

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
Ssh-uunen
  • 313
  • 1
  • 9
  • 1
    thanks for the edit, exemple 3 should return false IMHO because value is longer than 5 – Ssh-uunen Nov 08 '21 at 14:24
  • 1
    Does this answer your question? [HTML input checkValidity() always returns true even with minlength violations](https://stackoverflow.com/questions/66896018/html-input-checkvalidity-always-returns-true-even-with-minlength-violations) – thchp Nov 08 '21 at 14:26
  • 1
    No you have to use a `pattern` attribute to check that – Mister Jojo Nov 08 '21 at 14:26
  • 1
    https://stackoverflow.com/questions/10281962/is-there-a-minlength-validation-attribute-in-html5/10294291#10294291 your answer – Vitaliy Rayets Nov 08 '21 at 14:28
  • the pattern is ` pattern=".{0,5}"` – Mister Jojo Nov 08 '21 at 14:34
  • You are right, switching from `maxlength` to `pattern` does trigger the inital validity state correctly, thanks <3 – Ssh-uunen Nov 08 '21 at 14:35

0 Answers0