Forms
Forms are how users send information: logging in, searching, signing up, checking out. HTML gives you a lot of built-in functionality, including validation, keyboards suited to each input type, and date pickers, all without any JavaScript.
A basic form
Press Sign up with an empty or invalid email. The browser validates it for you. (In this preview, a successful submit shows the data that would be sent.)
| Part | Purpose |
|---|---|
action |
The URL that receives the data |
method |
get (data in the URL, for searches) or post (data in the request body, for anything that changes data or is private) |
name |
The key the value is sent under. Without a name, a field isn't submitted! |
<label for="id"> |
Connects text to an input: clicking the label focuses the input, and screen readers announce it |
Input types
Choosing the right type gives users the right keyboard on phones and free validation:
You can also wrap an input inside its <label>, as above, instead of using for/id.
Choices: checkboxes, radios and selects
- Radio buttons with the same
nameform a group where only one can be picked. - Checkboxes allow many choices.
<fieldset>+<legend>group related controls and label the group.
Built-in validation
| Attribute | Rule |
|---|---|
required |
Must not be empty |
minlength / maxlength |
Text length |
min / max / step |
Number and date ranges |
pattern |
Must match a regular expression |
type="email" / "url" |
Must look like an email / URL |
Client-side validation is for user experience, not security. Anyone can bypass it, so your server must always validate the data again.
Helpful attributes
autocomplete="email","name","new-password": lets browsers and password managers fill fields correctlyinputmode="numeric": shows a number keypad without number-input quirksdisabled,readonly,autofocus,placeholder(a hint, not a replacement for a label)
Practice
Build a course enrolment form with name, email, a <select> of tracks, a radio group for experience level, a "subscribe to newsletter" checkbox, and a comments <textarea>. Every field should have a label, and name and email should be required.
1.A form field has no name attribute. What happens on submit?
2.Which method should a login form use?