The required Attribute
You'll learn how to make form fields mandatory using the required attribute and how the browser validates them automatically.
What is the required Attribute?
The required attribute is a simple HTML attribute you add to form inputs to tell the browser: "This field must be filled out before the form can be submitted." It's part of HTML5's built-in constraint validation system, which means the browser handles the validation for you — no JavaScript needed!
Think of it like a bouncer at a club checking IDs. If someone doesn't have the required ID, they're not getting in. Similarly, if a required field is empty, the form won't submit.
How It Works
You add required directly to form elements like <input>, <textarea>, or <select>:
<form>
<label>Email:
<input type="email" name="email" required>
</label>
<label>Message:
<textarea name="message" required></textarea>
</label>
<button type="submit">Send</button>
</form>
When the user tries to submit this form with empty fields, the browser:
- Prevents the form from submitting
- Displays a built-in error message (like "Please fill out this field")
- Focuses on the first invalid field
Validation Behavior
The required attribute works differently depending on the input type:
- Text inputs: Must contain at least one character
- Checkboxes: Must be checked
- Radio buttons: At least one in the group must be selected
- Select elements: Must have a non-empty value selected
Key Takeaway: The required attribute provides instant, built-in form validation by preventing submission until mandatory fields are filled, with no JavaScript required.