Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to make a field required

Short answer

Add the required attribute to the field — the browser does not submit the form until it is filled in:

<form>
  <label>Name <input name="name" required></label>
  <button>Send</button>
</form>

Press "Send" with the field empty: a browser hint appears, and focus moves to the field.

An asterisk at the label

Required fields are usually marked with an asterisk. It can be added in CSS, and the :has() pseudo-class finds a label with a required field inside:

<style>
  label { display: block; margin-bottom: 8px; }
  label:has(:required)::after { content: " *"; color: crimson; }
</style>
 
<form>
  <label>Email <input type="email" required></label>
  <label>Phone <input type="tel"></label>
</form>

Explain the asterisk once above the form: "Fields marked with an asterisk are required".

Checkboxes and radio buttons

required works on a checkbox too — for example, for accepting the terms. In a group of radio buttons with one name, it is enough to put the attribute on one of them.

Common mistake

A field containing only spaces counts as filled in: required only checks that the value is not empty. Besides, browser validation is easy to bypass. So form data is always checked on the server as well — browser validation is just a convenience for the user.

Functions used in this recipe

  • required — Makes a field required: the form will not submit while it is empty.
  • :required — Matches fields with the `required` attribute; `:optional` matches those without it.
  • <form> — A form: collects data from its fields and sends it to the server.
  • <label> — A label for a form field.
  • ::after — Creates a virtual last child of the element — for icons, marks and decorations after the content.

Thanks for reading!

Donate to the site — we work hard for you.