Best practices when building forms
Viviane Martini
Posted on March 25, 2023
Building forms can be tricky sometimes, but if you add some extra details it can improve your site performance and accessibility.
Use Semantic HTML Form Elements
This will help when users need to navigate in your site using keybords. The tab key will automatically move between form fields.
Tags
<form>
Start your form with this tag on your html file, I know is simple but sometimes it's easy to forget.
<label>
This tag is really important, because it helps screen reader users, it announces the text within them.
here's how you can match/connect the tag label with the input:
<label for="name">Name</label>
<input type="text" id="name"/>
Using the label's for="
attribute with the id="
You can also code the input within the <label>
tags:
<label>
Nome
<input type="text" id="name"/>
</label>
❗️ Don't use <div>
when creating buttons!
❌ <div>Play video</div>
✔️ <button>Play video</button>
Using the correct tag not only helps with accessibility but with your site SEO.
<fieldset>
and <legend>
As the example below shows, the <fieldset>
element provides a grouping for a part of an HTML form, with a nested <legend>
element providing a caption for the <fieldset>
.
<fieldset>
<div class="fielset-wrapper">
<legend>Agendar próxima mentoria</legend>
<div class="col-3">
<div class="input-wrapper">
<label for="event-date">Data <span>(DD/MM/AAAA)</span></label>
<input type="date" id="event-date"/>
</div>
<div class="col-2">
<div class="input-wrapper">
<label for="event-begin">Das</label>
<input type="time" id="event-begin"/>
</div>
<div class="input-wrapper">
<label for="event-end">Até</label>
<input type="time" id="event-end"/>
</div>
</div>
</div>
</div>
</fieldset>
Validation
- add required fields
<div class="input-wrapper">
<label for="event-email">Email <span>(digite um email válido)</span></label>
<input type="text" id="event-email" required/>
</div>
- accept valid information, such as email and phone-number
For emails you can include rules such as:
- Uppercase (A-Z) and lowercase (a-z) English letters.
- Digits (0-9).
- Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
Use focus styling
Add contrasting colors
- remember to use outline, hover, contrast colors, you can also test your page colors if you need 😉
Flag up Errors
Try to add message errors or call attention adding some color to the missing input.
Checkbox
In case you want to custom your checkbox, you need to make sure its accessibility is not lost. Here's an example of how you can do it.
Wanna know more?
W3C
mdn web docs
The complete code you can find on my github page 💛 I coded for my Explore Class at Rocketseat.💜
Please share in the comments if you remember something else 🤩
Posted on March 25, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.