Here’s a step-by-step example of building a simple Form Validator in JavaScript using
string methods, DOM access, and conditional checks.
1. HTML Form Markup
We’ll create a form with fields for Name, Email, and Password, plus placeholders for error
messages.
html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Form Validation Example</title>
<style>
.error { color: red; font-size: 0.9em; }
.success { color: green; }
.form-field { margin-bottom: 1em; }
input { display: block; padding: 0.5em; width: 250px; }
</style>
</head>
<body>
<h2>Register</h2>
<form id="signup-form" novalidate>
<div class="form-field">
<label for="name">Name:</label>
<input type="text" id="name" />
<span class="error" id="name-error"></span>
</div>
<div class="form-field">
<label for="email">Email:</label>
<input type="email" id="email" />
<span class="error" id="email-error"></span>
</div>
<div class="form-field">
<label for="password">Password:</label>
<input type="password" id="password" />
<span class="error" id="password-error"></span>
</div>
<button type="submit">Submit</button>
<div id="form-success" class="success"></div>
</form>
<script src="validator.js"></script>
</body>
</html>
Each <input> has an accompanying <span> with id *-error to display error
messages.
We use novalidate on the <form> to disable the browser’s built-in validation so we
can handle it ourselves.
2. JavaScript Validation Logic (validator.js)
javascript
CopyEdit
// Grab DOM elements once
const form = document.getElementById('signup-form');
const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');
const passInput = document.getElementById('password');
const nameError = document.getElementById('name-error');
const emailError = document.getElementById('email-error');
const passError = document.getElementById('password-error');
const successMsg = document.getElementById('form-success');
// Utility: simple email regex
function isValidEmail(email) {
return /^\S+@\S+\.\S+$/.test(email);
}
// On form submission
form.addEventListener('submit', function(event) {
event.preventDefault(); // stop actual submit
clearErrors();
let valid = true;
// 1. Validate Name: non-empty and at least 3 characters
const nameVal = nameInput.value.trim();
if (nameVal === '') {
nameError.textContent = 'Name is required.';
valid = false;
} else if (nameVal.length < 3) {
nameError.textContent = 'Name must be at least 3 characters.';
valid = false;
}
// 2. Validate Email: non-empty and matches pattern
const emailVal = emailInput.value.trim();
if (emailVal === '') {
emailError.textContent = 'Email is required.';
valid = false;
} else if (!isValidEmail(emailVal)) {
emailError.textContent = 'Enter a valid email address.';
valid = false;
}
// 3. Validate Password: non-empty, min 6 chars, contains a number
const passVal = passInput.value;
if (passVal === '') {
passError.textContent = 'Password is required.';
valid = false;
} else if (passVal.length < 6) {
passError.textContent = 'At least 6 characters required.';
valid = false;
} else if (!/\d/.test(passVal)) {
passError.textContent = 'Include at least one digit.';
valid = false;
}
// If all checks passed
if (valid) {
successMsg.textContent = 'Form submitted successfully! 🎉';
// Here you could actually submit via AJAX or form.submit()
}
});
// Clear error messages
function clearErrors() {
[nameError, emailError, passError, successMsg].forEach(el => {
el.textContent = '';
});
}
3. How It Works
Step What It Does
Uses document.getElementById() to reference inputs and error
Grab DOM elements
spans.
event.preventDefault() Stops the browser’s default submit so we can validate first.
value.trim() removes whitespace; we check === '' or
Trim & check strings
.length < X.
isValidEmail() uses /^\S+@\S+\.\S+$/ and /\d/ to validate
Regex for email & digits
format.
Set .textContent of spans Display specific error messages next to each field.
Success message If all fields pass, show a confirmation in the DOM.