Forms are where users make mistakes. Good validation tells them what to fix, kindly and clearly.
Direct answer
To validate a form with JavaScript, listen for the form's submit event, check each field, show an error message next to any invalid field, and call event.preventDefault() to stop the form being sent until everything is valid. Always repeat the checks on the server too.
HTML
<form id="signup" novalidate>
<label>
Email
<input type="email" id="email" name="email">
</label>
<p id="email-error" role="alert"></p>
<label>
Password
<input type="password" id="password" name="password">
</label>
<p id="password-error" role="alert"></p>
<button type="submit">Sign up</button>
</form>
JavaScript
const form = document.querySelector('#signup');
const email = document.querySelector('#email');
const password = document.querySelector('#password');
const emailError = document.querySelector('#email-error');
const passwordError = document.querySelector('#password-error');
form.addEventListener('submit', (event) => {
let valid = true;
if (email.value.trim() === '') {
emailError.textContent = 'Please enter your email.';
valid = false;
} else if (!email.value.includes('@')) {
emailError.textContent = 'That does not look like an email address.';
valid = false;
} else {
emailError.textContent = '';
}
if (password.value.length < 8) {
passwordError.textContent = 'Use at least 8 characters.';
valid = false;
} else {
passwordError.textContent = '';
}
if (!valid) {
event.preventDefault();
}
});
Good practice
- Write messages that say how to fix the problem.
- Put the message next to the field.
- Use
role="alert"so screen readers announce errors. - Don't blame the user.
- Validate on the server as well; client checks can be bypassed.
HTML-only checks
Attributes like required, type="email" and minlength="8" give simple validation without JavaScript.
Related
JavaScript DOM tutorial and JavaScript for beginners.
Where Teyro fits
Teyro's Interactive Web Pages with JavaScript course teaches you to check forms, react to taps and typing and build lists from data, with a live page in every lesson. It is free to start.
The bottom line
Help the user fix it, and check again on the server.



