Listbox validation checks whether the user selected an acceptable option before a form is processed. For a required single-select, native HTML required is usually the first choice; JavaScript is useful when you need custom feedback or rules involving other controls.
<select id="language" name="Category" required>
<option value="">Select one</option>
<option value="PHP">PHP</option>
<option value="JavaScript">JavaScript</option>
</select>
Open the validation demo
When the first option has an empty value, required prevents submission until the user chooses a non-empty option.
<form id="languageForm" action="listbox-validation-demock.php" method="post">
<select id="language" name="Category" required>
<option value="">Select one</option>
<option value="PHP">PHP</option>
<option value="ASP">ASP</option>
<option value="JavaScript">JavaScript</option>
</select>
<button type="submit">Submit Form</button>
</form>
The original tutorial checked the selected string length. A clearer modern test is whether select.value is empty. Use textContent for a plain-text validation message.
const form = document.getElementById("languageForm");
const language = document.getElementById("language");
const message = document.getElementById("my_msg");
form.addEventListener("submit", (event) => {
if (language.value === "") {
event.preventDefault();
message.textContent = "Select one option before submitting.";
language.focus();
}
});
Listening for submit covers mouse clicks, keyboard submission and programmatic flows that dispatch a submit event. It is more complete than attaching logic only to a button’s click.
value.required ineffective.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.