Select one language, then submit the form. Leaving the placeholder selected shows the custom validation message without submitting.
document.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("f1");
const list = document.getElementById("l1");
const message = document.getElementById("my_msg");
form.addEventListener("submit", (event) => {
if (list.value === "") {
event.preventDefault();
message.textContent = "Select one option before submitting.";
message.className = "alert alert-warning mt-2";
list.focus();
}
});
});
<form id="f1" action="listbox-validation-demock.php" method="post">
<select id="l1" name="Category" required>
<option value="">Select One</option>
<option value="PHP">PHP</option>
<option value="JavaScript">JavaScript</option>
</select>
<div id="my_msg" aria-live="polite"></div>
<button type="submit">Submit Form</button>
</form>
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.