Before this lesson
Understand HTML forms, constraint validation and JavaScript submit events.
What you will be able to do
Combine native constraints with business validation and consistent mouse and keyboard submission.
Understand the mechanism
Express basic constraints with labels, required and maxlength, then apply business rules in submit. This covers Enter as well as clicks. preventDefault cancels native submission; it does not mean data was sent or saved.
Whitespace can pass some native required checks, so validate trimmed input. Explain how to correct errors. role=status suits noninterrupting result feedback. Associate per-field errors with their controls using aria-describedby when applicable.
Client validation improves usability; the server must validate length, types and permissions again. This example displays a local result and sends nothing to a server. Use textContent so markup-like nicknames remain text.
Runnable example
<form id="demo">
<label for="nickname">Nickname</label>
<input id="nickname" name="nickname" required maxlength="30">
<button>Check</button>
</form>
<p id="message" role="status"></p>
<script>
document.querySelector("#demo").addEventListener("submit", event => {
event.preventDefault();
const name = document.querySelector("#nickname").value.trim();
document.querySelector("#message").textContent = name ? "Hello, " + name : "Please enter a nickname.";
});
</script>
Trace and verify
Test empty input, whitespace, an ordinary name and the 30-character boundary. Submit with click and Enter. Enter <b>Alex</b> and verify literal text, not a bold element. Confirm no submission request in Network.
Common mistakes and boundaries
maxlength counting can differ from perceived characters for complex emoji. Do not clear input on every keystroke or communicate errors only through border color.
Practice challenge
Add a required course selection and preserve the entered name when selection is missing.
Reference solution and reasoning
Use an empty-value placeholder option and required select. Native validation handles missing input; business logic validates the allowed value before displaying results.