Form Inputs and Validation
The type attribute of <input> changes the kind of box you get. On phones, the right type also opens the right keyboard.
Good forms feel effortless: the right keyboard pops up, the date opens a calendar, mistakes are pointed out before you submit. Bad forms are one of the main reasons people leave a website without buying or signing up. Choosing the right input types and validation rules is a small effort with a big payoff.
email- checks for an @ and shows an email keyboardtel- number pad for phone numbersnumber- only numbers, withmin,maxandstepdate,time- a calendar or clock pickerrange- a slider;color- a colour pickercheckbox- tick many;radio- pick one from a group (samename)password- hides the letters;file- choose a file
<!DOCTYPE html>
<html>
<body>
<form>
<label>Email <input type="email" name="email" required></label><br><br>
<label>Mobile <input type="tel" name="phone" pattern="[0-9]{10}" placeholder="10 digits"></label><br><br>
<label>Quantity <input type="number" name="qty" min="1" max="10" value="1"></label><br><br>
<label>Delivery date <input type="date" name="day"></label><br><br>
<label>Budget <input type="range" name="budget" min="500" max="5000" step="500"></label><br><br>
<p>Payment:</p>
<label><input type="radio" name="pay" value="upi" checked> UPI</label>
<label><input type="radio" name="pay" value="card"> Card</label>
<label><input type="radio" name="pay" value="cod"> Cash on delivery</label><br><br>
<label><input type="checkbox" name="gift"> Gift wrap</label><br><br>
<label>City
<select name="city">
<option>Delhi</option>
<option>Mumbai</option>
<option selected>Bengaluru</option>
</select>
</label><br><br>
<label>Note<br><textarea name="note" rows="3" cols="30"></textarea></label><br><br>
<button type="submit">Place order</button>
</form>
</body>
</html>▶ Try it yourselfBuilt-in validation
The browser can check a form before it is sent, with no JavaScript:
Built-in validation gives instant feedback without writing any code, and works even if JavaScript fails to load. The browser shows a message near the field and focuses it. For more control over the look of messages, developers later add JavaScript, but these attributes remain the foundation.
required- the box must not be emptyminlength/maxlength- number of lettersmin/max- smallest and biggest number or datepattern- a rule the text must match, such as exactly 10 digits
Press Place order with an empty email to see the browser's message.
<label> to every input (wrap the input, or use for and id). Tapping the label then selects the box, and screen readers read its name.- The input type decides the kind of field and the phone keyboard.
- required, minlength, min/max and pattern validate without JavaScript.
- Label every input; always validate again on the server.
