Forms, feedback, and the final audit
Validate with browser constraints
Declare task-title and due-date rules in HTML, inspect validity in JavaScript, and keep server validation as a separate boundary.
The task editor can express many input rules directly in HTML. required, input types, min, max, minlength, maxlength, and pattern let the browser block an invalid submission and expose a ValidityState to your code.
Start declaratively, then use checkValidity() or reportValidity() when a scripted workflow needs the result. Use setCustomValidity() only for a rule HTML cannot express, and clear the message as soon as the value becomes valid. A stale custom error keeps the control invalid forever.
<label>Task title
<input name="title" required minlength="3" maxlength="80">
</label>
<label>Due date <input name="due" type="date"></label>
<script>
const titleInput = document.querySelector("[name=title]")
const taskTitles = new Set(["write homepage"])
titleInput.addEventListener("input", () => {
const duplicate = taskTitles.has(titleInput.value.trim().toLowerCase())
titleInput.setCustomValidity(duplicate ? "Use a unique task title." : "")
})
</script>
Browser constraint validation improves immediate feedback; it is not a security boundary. A client can disable JavaScript, alter markup, or send an HTTP request directly. The server must validate every accepted field against the same business rules.
Do not replace the browser’s message with a vague toast. Keep the error associated with the field, move focus to the first invalid control when appropriate, and explain how to fix it. The existing free Forms course covers labels, submission, FormData, files, and server handling in depth.
Date input presentation depends on browser and locale, while its submitted value uses a defined date format. Avoid parsing a displayed localized string yourself. Read the control value or valueAsDate according to the actual rule you need.
Try an empty title, two characters, a valid title, and a duplicate. Inspect validity.valueMissing, tooShort, and customError. Correct each value and confirm the error clears. Submit with only the keyboard and verify focus and the browser message identify the field that needs work. If a formerly duplicate title remains invalid, ensure every input change calls setCustomValidity("") when the duplicate condition is false.
Lesson completed