I recently received the following question:
I tried to add the
required
attribute to the<select>
element but now my page won't validate. Is therequired
not allowed on a<select>
element?
Answer
First of all, the required
attribute is used to specify that the element is a required part of the form submission.
The required
attribute can be written in the following ways:
<select required="required">
<select required='required'>
<select required=required>
<select required="">
<select required=''>
<select required>
The <select>
element does allow the required
attribute. However, there are some requirements associated with using the required
attribute with the <select>
element:
A <select> element with a required attribute and without a multiple attribute, and whose size is "1", must have a child option element.
The first child option element of a <select> element with a required attribute and without a multiple attribute, and whose size is “1”, must have either an empty value attribute, or must have no text content.
So, if you are using the required
attribute with a <select>
element
- you must have at least one child element
- the first child element must have either an empty value attribute OR
- the first child element must have no text content.
Example 1
The example below has a <select>
element with the required
attribute. This example is not considered valid as the first child element has no empty value attribute, or no content.
<form action="#" method="post">
<div>
<label for="State">State</label>
<select required aria-required="true" id="State">
<option>Choose</option>
<option value="act">ACT</option>
<option value="nsw">NSW</option>
<option value="nt">NT</option>
<option value="qld">QLD</option>
<option value="sa">SA</option>
<option value="tas">TAS</option>
<option value="vic">VIC</option>
<option value="wa">WA</option>
</select>
</div>
</form>
Example 2
This example is considered valid as the first child element has an empty value attribute.
<form action="#" method="post">
<div>
<label for="State">State</label>
<select required aria-required="true" id="State">
<option value="">Choose</option>
<option value="act">ACT</option>
<option value="nsw">NSW</option>
<option value="nt">NT</option>
<option value="qld">QLD</option>
<option value="sa">SA</option>
<option value="tas">TAS</option>
<option value="vic">VIC</option>
<option value="wa">WA</option>
</select>
</div>
</form>
Example 3
This example is also considered valid as the first child element has no content.
<form action="#" method="post">
<div>
<label for="State">State</label>
<select required aria-required="true" id="State">
<option></option>
<option value="act">ACT</option>
<option value="nsw">NSW</option>
<option value="nt">NT</option>
<option value="qld">QLD</option>
<option value="sa">SA</option>
<option value="tas">TAS</option>
<option value="vic">VIC</option>
<option value="wa">WA</option>
</select>
</div>
</form>