JavaScript
Tutorial: validate a form with JavaScript
Add real-time validation to an HTML form using JavaScript, no external libraries needed.
The browser already validates some things on its own (required, type="email"), but for custom error messages you need JavaScript. Let's validate a simple sign-up form.
Step 1: the HTML
<form id="signup-form">
<input type="text" id="username" placeholder="Username" />
<input type="password" id="password" placeholder="Password" />
<button type="submit">Sign up</button>
<p id="error" style="color: #ff6b6b;"></p>
</form>
Step 2: listen for the submit event
const form = document.querySelector('#signup-form');
const error = document.querySelector('#error');
form.addEventListener('submit', (event) => {
event.preventDefault();
error.textContent = '';
const username = document.querySelector('#username').value;
const password = document.querySelector('#password').value;
if (username.length < 3) {
error.textContent = 'Username must be at least 3 characters.';
return;
}
if (password.length < 6) {
error.textContent = 'Password must be at least 6 characters.';
return;
}
console.log('Form is valid, submitting...');
});
event.preventDefault() stops the page from reloading (a form's default behavior). Without that line, your error message would flash and disappear in a fraction of a second, and you'd think your code was broken when really the browser was "helping" too much.
Step 3: validate as the user types (optional, extra credit)
document.querySelector('#password').addEventListener('input', (event) => {
const value = event.target.value;
error.textContent =
value.length > 0 && value.length < 6
? 'Still too short...'
: '';
});
The input event fires every time the user types something. This lets you give instant feedback instead of waiting for them to try submitting the form.
What did you just learn?
- How to listen for the
submitevent and prevent page reloads withpreventDefault(). - How to validate values with simple conditionals.
- How to give real-time feedback with the
inputevent.