Phase 1HTML Fundamentals

#4 Forms

input, select, textarea, validation

The form element

Forms collect user input and send it to a server. The <form> element wraps all form controls and defines where and how data is sent:

Basic form
<form action="/submit" method="POST">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>

  <label for="password">Password:</label>
  <input type="password" id="password" name="password" minlength="8" required>

  <button type="submit">Sign in</button>
</form>

Input types

HTML5 provides many specialized input types with built-in validation:

Input types
<input type="text" placeholder="Your name">
<input type="email" placeholder="you@example.com">
<input type="password" minlength="8">
<input type="number" min="0" max="100" step="1">
<input type="date">
<input type="color" value="#3b82f6">
<input type="range" min="0" max="100">
<input type="file" accept="image/*">
<input type="checkbox" id="agree">
<input type="radio" name="plan" value="free">

Select, textarea, and fieldset

More form elements
<select name="role">
  <option value="">Select a role</option>
  <optgroup label="Engineering">
    <option value="frontend">Frontend</option>
    <option value="backend">Backend</option>
  </optgroup>
</select>

<textarea name="bio" rows="4" cols="50"
  placeholder="Tell us about yourself"></textarea>

<fieldset>
  <legend>Shipping address</legend>
  <label for="street">Street:</label>
  <input type="text" id="street" name="street">
</fieldset>

Validation attributes

HTML5 validation happens natively in the browser before submission:

Validation
<input type="text" required>                   <!-- Must fill -->
<input type="email">                            <!-- Must be email -->
<input type="text" minlength="3" maxlength="20"> <!-- Length -->
<input type="number" min="1" max="99">          <!-- Range -->
<input type="text" pattern="[A-Za-z]{3,}">      <!-- Regex -->

Your turn

Try the form commands below:

terminal — browser
user@stemlegacy:~$