HTML & CSSEasy
What is the required attribute?
required is a boolean attribute that marks a form control as mandatory. The browser blocks submission if the field is empty, focuses the first invalid field, shows a native message, and exposes the requirement to assistive technology. It works on most <input> types, <select> and <textarea>, and for radio groups on any radio with the shared name.
Behavior
- Empty required fields fail constraint validation, so the
submitevent does not fire. - CSS pseudo-classes:
:required,:optional,:invalid,:valid, and:user-invalid/:user-valid, which only match after the user has interacted (Baseline since 2023), so you avoid showing errors before the user types. - JavaScript:
input.validity.valueMissing,form.checkValidity(),form.reportValidity(),input.setCustomValidity("message").
Special cases
- Checkbox: must be checked (consent boxes).
- Radio group: one option must be selected.
<select>: the first option must have an emptyvalueto act as a placeholder ("Choose…").- File inputs: a file must be chosen.
- Ignored for
hidden,range,colorand button types, and fordisabledorreadonlyfields.
UX and accessibility
- Show which fields are required visually (an asterisk with a legend, or "(required)" text), not only with color.
- Screen readers announce "required" automatically.
- Use
aria-required="true"only on custom controls that are not native inputs. - Use
novalidateon the form if you render your own messages, but keeprequiredfor semantics.
Remember
Client-side validation is for user experience; always validate on the server too.
Code example
html
1<style>2 body { font-family: system-ui; }3 form { display: grid; gap: 10px; max-width: 320px; }4 input:user-invalid, select:user-invalid { border: 2px solid #dc2626; } /* only after interaction */5 input:user-valid { border: 2px solid #16a34a; }6 .req::after { content: " *"; color: #dc2626; }7</style>8<p><span class="req"></span> = required</p>9<form>10 <label class="req" for="n">Name</label>11 <input id="n" name="name" required>1213 <label class="req" for="topic">Topic</label>14 <select id="topic" name="topic" required>15 <option value="">Choose…</option>16 <option>Billing</option><option>Technical</option>17 </select>1819 <fieldset><legend class="req">Contact method</legend>20 <label><input type="radio" name="contact" value="email" required> Email</label>21 <label><input type="radio" name="contact" value="phone"> Phone</label>22 </fieldset>2324 <label><input type="checkbox" name="agree" required> I agree to the privacy policy</label>25 <button>Submit</button>26</form>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.