HTML Form Validation
HTML5 has built-in form validation — no JavaScript needed for basic checks. The browser validates inputs before submission and shows error messages automatically, styled to match the OS.
Built-in Validation Attributes
Example 1 — Full Validated Registration Form
<form novalidate> <!-- required: must not be empty --> <input type="text" name="name" required/> <!-- type="email": must be valid email format --> <input type="email" name="email" required/> <!-- minlength/maxlength: text length limits --> <input type="password" name="pw" minlength="8" maxlength="64" required/> <!-- min/max: number range --> <input type="number" name="age" min="13" max="120"/> <!-- pattern: custom regex validation --> <input type="text" name="username" pattern="[a-z0-9_]{3,20}" title="3-20 chars: lowercase letters, numbers, underscore"/> <button type="submit">Register</button> </form>
The browser shows native error tooltips automatically. title="" is shown as the error hint for pattern validation.
Custom Error Messages
Example 2 — Custom Validation with JavaScript
<input type="email" id="email" required/> <span id="email-error" style="color:red;display:none"></span> <script> var inp = document.getElementById('email'); inp.addEventListener('invalid', function() { document.getElementById('email-error').textContent = 'Please enter a valid email address'; document.getElementById('email-error').style.display = 'block'; }); </script>
The invalid event fires when the browser's validation fails. Use setCustomValidity() for fully custom messages.
Validation Attributes
requiredField must not be empty. Browser blocks submission and shows error.
minlength/maxlengthText input character limits. Works on text, password, textarea.
min/maxNumber and date range limits. min="2024-01-01" for date inputs.
patternRegex pattern. [a-z]+ = only lowercase letters. Use title="" for the error hint.
novalidateOn the form element: disables browser validation. Use when building custom JS validation.
Always Validate Server-Side Too
HTML validation only runs in the browser. Anyone can bypass it by sending a request directly to your server (using curl, Postman, or browser devtools). Always validate again on the server for security.