Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT FORMS / CHAPTER 05 / Learn / LESSON 07
Theory. When your rule is more complex than attributes, use the Constraint Validation API: el.setCustomValidity("text") marks the field invalid with a message. el.setCustomValidity("") — the empty string — returns it to valid.
The key is "clear on change": if you set a message and never remove it, the field stays invalid even after the user fixes it. So listen to the input event and each time set either a message or "".
Small example:
field.addEventListener("input", () => { if (field.value.length < 3) field.setCustomValidity("too short"); else field.setCustomValidity(""); });
After that field.validity.valid is false and field.validationMessage is your message. checkValidity() returns a boolean; reportValidity() shows the browser bubble.
Common mistake: setCustomValidity without resetting; resetting only on submit; setting the message on the wrong element.
<form id="f"><input id="u1" name="u1" type="text"><input id="u2" name="u2" type="text"><button type="submit">Save</button></form>The empty string in setCustomValidity returns the field to valid. Without clearing, the error stays forever.
Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›