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 06
Theory. The browser can validate on its own — with attributes: required, type="email" / "number", min and max for numbers, minlength/maxlength for length, and pattern (a regular expression) for text. Each of them makes the field invalid without any logic from you.
Read the state from el.validity.valid (or el.checkValidity()). You can also set the attributes from JS: el.required = true; el.type = "email"; el.min = 18; el.pattern = "[A-Z]{3}[0-9]{2}".
Small examples:
const age = document.querySelector("#age"); age.type = "number"; age.min = 18; age.max = 99;
A pattern must match the whole value: [A-Z]{3}[0-9]{2} accepts "ABC12" but not "abc12" and not "ABC123".
Important: client-side validation is for the user's convenience. It does NOT replace server checks — anyone can bypass the browser.
Common mistake: type="number" for values that are not numbers (phone, postal code); forgotten required — an empty field is valid!
<form id="f"><input id="email" name="email" type="text"><input id="age" name="age" type="text"><input id="code" name="code" type="text"><button type="submit">Send</button></form>Attributes turn the browser into a validator: type, required, min/max, pattern.
Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›