← Back to Tutorials Chapter 6

Forms & Inputs

The Form Element

Forms are used to collect user input and send it to a server:

<form action="/submit" method="POST">
  <!-- form elements go here -->
  <button type="submit">Submit</button>
</form>

Form Attributes

Input Types

HTML5 offers many input types for different kinds of data:

<input type="text" name="username">
<input type="email" name="email">
<input type="password" name="password">
<input type="number" name="age" min="0" max="150">
<input type="tel" name="phone">
<input type="url" name="website">
<input type="date" name="birthday">
<input type="time" name="appointment">
<input type="color" name="favorite-color">
<input type="range" name="volume" min="0" max="100">
<input type="file" name="document" accept=".pdf,.doc">
<input type="checkbox" name="subscribe" value="newsletter">
<input type="radio" name="gender" value="male">
<input type="hidden" name="csrf-token" value="abc123">

Labels & Accessibility

Always associate a <label> with each input:

<label for="email">Email Address:</label>
<input type="email" id="email" name="email" required>

<!-- Or wrap input inside label -->
<label>
  <input type="checkbox" name="agree">
  I agree to the terms
</label>

Textareas & Selects

<textarea name="message" rows="5" cols="40" placeholder="Your message..."></textarea>

<select name="country">
  <option value="">Select a country</option>
  <option value="in">India</option>
  <option value="us">United States</option>
  <option value="uk">United Kingdom</option>
</select>

Fieldset & Legend

Group related fields together:

<fieldset>
  <legend>Personal Information</legend>
  <label for="fname">First Name:</label>
  <input type="text" id="fname" name="fname">
  <label for="lname">Last Name:</label>
  <input type="text" id="lname" name="lname">
</fieldset>

HTML5 Form Validation

<input type="text" required>                      <!-- Required field -->
<input type="email">                               <!-- Must be valid email -->
<input type="text" minlength="3" maxlength="20">   <!-- Length limits -->
<input type="number" min="1" max="10">             <!-- Range limits -->
<input type="text" pattern="[A-Za-z]+">            <!-- Regex pattern -->
Custom validation messages: Use JavaScript's setCustomValidity() to override default messages.

Complete Form Example

<form action="/register" method="POST">
  <fieldset>
    <legend>Create Account</legend>

    <label for="name">Full Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <label for="pass">Password (min 8 chars):</label>
    <input type="password" id="pass" name="pass" minlength="8" required>

    <label>
      <input type="checkbox" name="terms" required>
      I accept the Terms & Conditions
    </label>

    <button type="submit">Register</button>
  </fieldset>
</form>

Practice Task

Create a feedback form with: