Ssh-uunen
Ssh-uunen

Reputation: 311

HTML input validity initial state

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

Upvotes: 2

Views: 92

Answers (0)

Related Questions