required
Requires a value before submission.
Form validation checks whether input is acceptable before the application trusts or submits it.
if (!form.checkValidity()) {
form.reportValidity();
return;
}
Events & Forms
HTML validation attributes such as required, minlength, type and pattern provide a strong first layer.
JavaScript can call checkValidity, reportValidity and setCustomValidity to integrate custom validation with browser behavior.
Validation is not security. The server must validate again. Client-side validation is for faster feedback and better usability.
Requires a value before submission.
Adds built-in rules for email, url, number and more.
Returns whether the form or field is valid.
Sets a custom validation message.
Examples
function validateTitle() {
title.setCustomValidity(title.value.trim().length < 3 ? "Use at least 3 characters." : "");
}
error.textContent = "Title is too short"; // The browser still thinks the field is valid.
Code patterns
These examples are the event patterns you will reuse constantly: listen, inspect, prevent, delegate, validate and submit.
Use the browser validation model.
if (!form.checkValidity()) {
form.reportValidity();
}
Set an error string or clear it with an empty string.
field.setCustomValidity("Choose at least 8 characters.");
field.reportValidity();
Always clear when the value becomes valid.
field.setCustomValidity("");
Give feedback as values change.
field.addEventListener("input", validateField);
Rules that matter
Events are user-facing code. Good handlers stay small, respect native behavior and keep visual, semantic and data state aligned.
required and type cover many common cases.
It integrates with browser validation.
A stale custom error keeps the field invalid.
Client validation can be bypassed.
Tell users how to fix the field.
Help users find the invalid field without trapping them.
Production thinking
Validation is where data quality, user experience and security boundaries meet.
Errors should be associated with fields and written in clear language.
Production forms need both client-side feedback and server-side enforcement.
Validation quality affects conversion and trust more than ranking directly.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
If you can explain what fires, where it fires and what default behavior remains, you understand the interaction.
Chapter checkpoint
Finish this chapter by turning the lessons into a small practical proof.
Create a form with validation, status feedback and keyboard-friendly submit behavior.
Can a user complete the form without a mouse?