Problem Statement
Which attribute makes a form field mandatory?
Explanation
The required attribute makes a form field mandatory. When you add required to an input, select, or textarea, the browser prevents form submission if that field is empty. The browser displays an error message and focuses on the empty required field. This provides immediate feedback without needing server validation. Required is a boolean attribute, meaning you just add the word required without a value. It works with most input types including text, email, password, number, url, checkbox, radio, file, and date. For select dropdowns, required ensures an option other than the first one is selected. For checkboxes, required means the checkbox must be checked. However, required is only client-side validation and can be bypassed. Always validate required fields on the server as well for security.
Code Solution
SolutionRead Only
<!-- Required text input -->
<form>
<label for="name">Name (required):</label>
<input type="text"
id="name"
name="name"
required>
<button type="submit">Submit</button>
</form>
<!-- Required email -->
<form>
<input type="email"
name="email"
placeholder="Email"
required>
<button type="submit">Subscribe</button>
</form>
<!-- Required checkbox -->
<form>
<label>
<input type="checkbox"
name="terms"
required>
I agree to terms (required)
</label>
<button type="submit">Register</button>
</form>
<!-- Required select -->
<form>
<select name="country" required>
<option value="">Choose country</option>
<option value="us">USA</option>
<option value="uk">UK</option>
</select>
<button type="submit">Continue</button>
</form>