The required attribute prevents form submission if the field is empty. When you add required to an input, the browser checks if it has a value before allowing form submission. If empty, the browser shows an error message and focuses on the empty field. This client-side validation provides immediate feedback without a server round trip. The required attribute is a boolean attribute, meaning you just add the word required without a value. It works with text, email, password, number, url, checkbox, radio, and file inputs. For select dropdowns and textareas, required ensures a value is selected or entered. However, client-side validation is not sufficient for security. Users can bypass it by disabling JavaScript or using browser tools. Always validate required fields on the server as well. The required attribute improves user experience but is not a replacement for server-side validation.
Example code
<!-- Required text inputs -->
<form action="/submit" method="POST">
<label for="name">Name (required):</label>
<input type="text"
id="name"
name="name"
required>
<label for="email">Email (required):</label>
<input type="email"
id="email"
name="email"
required>
<label for="message">Message:</label>
<input type="text" id="message" name="message">
<button type="submit">Submit</button>
</form>
<!-- Required checkbox -->
<form>
<label>
<input type="checkbox" name="terms" required>
I agree to the terms (required)
</label>
<button type="submit">Register</button>
</form>
<!-- Mix of required and optional -->
<form>
<input type="text" name="firstname" placeholder="First Name" required>
<input type="text" name="lastname" placeholder="Last Name" required>
<input type="text" name="middlename" placeholder="Middle Name (optional)">
<input type="email" name="email" placeholder="Email" required>
<input type="tel" name="phone" placeholder="Phone (optional)">
<button type="submit">Submit</button>
</form>