HTML Forms & Input Types

Difficulty: Beginner

Question

How do HTML forms work? What input types are available, and how do you validate input on the client and the server?

Answer

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.

What happens on submit

  1. The user presses a submit button or Enter in a text field.
  2. The browser runs constraint validation. If any field fails, it shows a message and stops.
  3. A submit event fires. JavaScript can call event.preventDefault() to handle it with fetch.
  4. Otherwise the browser serialises the fields that have a 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.
  1. The 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.

Input types worth knowing

TypeWhat you get
email, urlFormat validation and an adapted keyboard
telPhone keypad on mobile; no format validation, so add pattern
numberNumeric spinner with min, max, step; avoid for OTPs and card numbers
date, time, datetime-localNative pickers
checkbox, radioRadios with the same name are mutually exclusive
fileaccept and multiple; needs multipart/form-data
range, color, search, password, hiddenSpecialised 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.

Validation in layers

  • HTML attributes: required, minlength, maxlength, pattern, min, max, step, type.
  • Constraint Validation API: input.validity, checkValidity(), reportValidity() and setCustomValidity('message') for custom rules such as "passwords must match".
  • CSS: :user-invalid styles a field only after the user has interacted with it, avoiding red borders on page load.
  • Server: re-check every field, because anyone can bypass the browser with DevTools or curl. Return field-level errors and show them next to the inputs.

Accessibility essentials

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.

Submitting a form. The browser validates first, then sends named fields; the server validates again.
  1. User → Browser: Clicks submit
  2. Browser → User: Shows message if a field is invalid
  3. User → Browser: Fixes the field and resubmits
  4. Browser → Server: POST named fields after validation passes
  5. Server → Browser: Re-validates, returns success or field errors
  6. Browser → User: Shows confirmation or server errors

Code examples

Accessible form with native validation

<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.

Custom rule and fetch submission with FormData

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.

Key points

  • Only fields with a name attribute and not disabled are submitted.
  • GET puts data in the URL; POST puts it in the body. Default method is GET.
  • File uploads need method="post" and enctype="multipart/form-data".
  • Buttons inside a form default to type="submit".
  • Client-side validation is UX; server-side validation is security.
  • Every input needs a real label; placeholder is not a label.

Common follow-up questions

  • What is the difference between disabled and readonly inputs on submit?
  • How would you prevent double submission of a payment form?
  • When would you use novalidate on a form?
  • How does :user-invalid differ from :invalid?
  • Why should you not use type="number" for a phone number or OTP?

Interview tips

  • State clearly that client-side validation can be bypassed and the server must validate again.
  • Mention autocomplete and inputmode; they show you care about real users on mobile.
  • If asked to write a form, start with labels and fieldsets before adding validation attributes.

Concepts covered

Form submission, Input types, Constraint Validation API, FormData, Labels and fieldsets

More HTML & CSS Interview questions