Difficulty: Beginner
How do HTML forms work? What input types are available, and how do you validate input on the client and the server?
An HTML form groups inputs and sends their name=value pairs to the URL in action using the HTTP method in method when the user submits. HTML5 input types such as email, tel, number and date give you the right mobile keyboard and built-in validation through attributes like required, pattern and min, but client-side checks are only for user experience; the server must validate everything again.
submit event fires. JavaScript can call event.preventDefault() to handle it with fetch.name and are not disabled:method="get" (the default) appends them to the URL as a query string, good for search and filters.method="post" sends them in the request body, used for anything that changes data.enctype decides the body format: application/x-www-form-urlencoded by default, multipart/form-data for file uploads.A <button> inside a form defaults to type="submit". Forgetting type="button" on a "Show password" toggle is a classic bug that submits the form.
| Type | What you get |
|---|---|
email, url | Format validation and an adapted keyboard |
tel | Phone keypad on mobile; no format validation, so add pattern |
number | Numeric spinner with min, max, step; avoid for OTPs and card numbers |
date, time, datetime-local | Native pickers |
checkbox, radio | Radios with the same name are mutually exclusive |
file | accept and multiple; needs multipart/form-data |
range, color, search, password, hidden | Specialised controls |
For a 6-digit OTP use type="text" inputmode="numeric" autocomplete="one-time-code", which shows a number pad and lets phones autofill the SMS code. autocomplete values like email, tel and postal-code speed up checkout considerably.
required, minlength, maxlength, pattern, min, max, step, type.input.validity, checkValidity(), reportValidity() and setCustomValidity('message') for custom rules such as "passwords must match".:user-invalid styles a field only after the user has interacted with it, avoiding red borders on page load.curl. Return field-level errors and show them next to the inputs.Every input needs a <label for> (placeholders disappear and are not labels). Group radios and checkboxes in <fieldset> with a <legend>. Connect error text with aria-describedby and mark failing fields with aria-invalid="true". Keep errors visible as text, not just a red border, since colour alone fails users with colour blindness.
<form action="/api/register" method="post">
<label for="name">Full name</label>
<input id="name" name="name" required minlength="2" autocomplete="name">
<label for="email">Email</label>
<input id="email" name="email" type="email" required autocomplete="email">
<label for="phone">Mobile number</label>
<input id="phone" name="phone" type="tel" required
pattern="[6-9][0-9]{9}" autocomplete="tel-national"
aria-describedby="phone-hint">
<p id="phone-hint">10 digits, no country code</p>
<fieldset>
<legend>Internship mode</legend>
<label><input type="radio" name="mode" value="remote" checked> Remote</label>
<label><input type="radio" name="mode" value="onsite"> On-site</label>
</fieldset>
<label for="resume">Resume (PDF)</label>
<input id="resume" name="resume" type="file" accept="application/pdf">
<button type="submit">Apply</button>
</form>
Labels, autocomplete and the right input types do most of the work before any JavaScript runs. The pattern only allows Indian mobile numbers starting with 6 to 9.
const form = document.querySelector('#signup');
const pwd = form.elements.password;
const confirm = form.elements.confirm;
confirm.addEventListener('input', () => {
// Empty string means valid; any text marks the field invalid
confirm.setCustomValidity(
confirm.value === pwd.value ? '' : 'Passwords do not match'
);
});
form.addEventListener('submit', async (event) => {
event.preventDefault();
if (!form.reportValidity()) return; // shows native messages
const body = new FormData(form); // includes files
const res = await fetch('/api/signup', { method: 'POST', body });
// Do not set Content-Type: the browser adds the multipart boundary
if (!res.ok) showServerErrors(await res.json());
});
setCustomValidity plugs custom rules into native validation, and FormData serialises every named field, including files, for fetch.
Form submission, Input types, Constraint Validation API, FormData, Labels and fieldsets