HTML Guide for required
The W3C HTML validator issue arises when a <select> element is marked as required but doesn’t contain any <option> elements. The semantic purpose of a <select> element is to provide a list of options for the user to select from. If it is marked as required, it implies the user must make a selection from available options.
Here is an explanation of the involved elements and attributes:
-
<select>: This represents a drop-down list in an HTML form.
- required: When this attribute is present, it means the user must select an option before submitting the form. It cannot be empty.
- multiple: This boolean attribute allows multiple selections if present.
- size: This attribute specifies the number of visible options. If greater than 1 and multiple is not set, it turns the drop-down into a list box.
If the multiple attribute is not present and the size attribute is not greater than 1, you need at least one <option> element for the <select> to be valid when required is used.
To resolve this, ensure that your <select> element contains at least one <option>:
<label for="choices">Choose an option:</label>
<select id="choices" name="choices" required>
<option value="">--Please choose an option--</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
This example includes a placeholder option with an empty value to prompt the user to select an option and other valid options. The value for the placeholder is empty, which is a common practice for required fields to prevent it from being selected by default.
The aria-required attribute is used to indicate to screen reader users that a form input is required. As there is now in HTML a general required attribute which works with most user agents, it’s unnecessary to use both at the same time. In general, you can rely solely on the required attribute, unless you want to provide backwards compatibility on old screen reader software versions.
Example:
<form action="order.">
<!-- This will raise a warning on unnecesary attributes -->
<input id="city" name="city" aria-required="true" required />
<!-- You can use this instead -->
<input id="city" name="city" required />
</form>
The boolean required attribute can only be used with certain types of inputs. Check the input type is one of the allowed.
The required attribute, if present, indicates that the user must specify a value for the input before the owning form can be submitted.