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 DOM / CHAPTER 04 / Learn / LESSON 09
Validation checks input before acting. If the value is bad — show a message in #err; if good — clear the error and continue.
Typical: Number(input.value) < 1 → "too small". Empty input is also a problem.
Mini example:
document.querySelector("#check").addEventListener("click", () => { const n = Number(document.querySelector("#amount").value); const err = document.querySelector("#err"); if (n < 1) err.textContent = "too small"; else err.textContent = ""; });
Common mistake: validating only in your head without writing to the DOM; or comparing a string to a number without Number.
<input id="amount" type="text" value="0" /><button id="check" type="button">Check</button><p id="err"></p>Show the error in the DOM, not only in your head.
Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›