Web Fundamentals · Lesson 4 of 10 · 4 min
Advanced Forms & Input Validation
This is where you show you think about security, user experience, and accessibility, not just data collection.
After this, you'll be able to explain the critical difference between client-side and server-side validation, implement accessible error messages that work for everyone, and discuss the trade-offs of different validation strategies. This isn't just about the required attribute; it's about building robust, professional-grade forms.
Client vs. Server: The Non-Negotiable Split
Every form needs two independent layers of validation. Client-side validation runs in the browser for user experience. Server-side validation runs on the server for security. They are not alternatives. You must have both.
Client-side validation gives immediate feedback. It prevents the user from submitting a form with obvious errors, saving a frustrating round-trip to the server. This is purely for UX.
Server-side validation is your application's source of truth and security. The client can be manipulated; JavaScript can be disabled, API requests can be forged. Never trust any data that arrives at your server. Always re-validate everything.
The interview question: "Why do we need both client-side and server-side validation?" Your answer: "Client-side is for a better user experience through immediate feedback. Server-side is for security and data integrity, as client-side checks can always be bypassed. They serve different, equally critical purposes."
Choosing Your Client-Side Tools
On the client, you have two main tools: built-in HTML5 validation and custom JavaScript.
HTML5 attributes (required, type="email", pattern, minlength) are your first line of defense. They are declarative, fast, and work without JavaScript. The :invalid CSS pseudo-class provides a simple hook for styling invalid fields.
The trap: Relying solely on built-in validation. The error messages and UI are inconsistent across browsers and can't be styled reliably. More importantly, they can't handle any logic that involves more than one field, like a "confirm password" input.
For any real-world form, you need JavaScript. It gives you full control over when validation runs (on blur, on submit), the logic (cross-field validation, async checks), and how errors are displayed. To enable custom JS validation, add the novalidate attribute to your <form> element. This tells the browser not to interfere.
How to Implement Accessible Error Messages
A red border isn't enough. If a screen reader user can't understand what's wrong and how to fix it, your form is broken.
You need three things for an accessible error message:
- Set
aria-invalid="true"on the<input>when its value is invalid. This tells assistive technology the field has an error. - Place the error message in its own element, like a
<div>or<span>, and give it a uniqueid. - Connect the input to its error message using
aria-describedby. The value of this attribute should be theidof the error message element.
This linkage ensures a screen reader will announce the error message when the user focuses on the invalid input. For an even better experience, add aria-live="polite" to the error message container so updates are announced as they appear.
Finally, manage focus. When a form submission fails, programmatically move focus to the first field with an error. This saves keyboard and screen reader users from having to hunt for the problem.
A Practical JavaScript Validation Pattern
Here is the minimum viable structure for accessible custom validation. It combines the novalidate attribute, a submit handler, and the necessary ARIA attributes.
<form id="profileForm" novalidate>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" aria-describedby="password-error">
<div id="password-error" class="error-message" role="alert" aria-live="polite"></div>
</div>
<button type="submit">Update</button>
</form>
<script>
const form = document.getElementById('profileForm');
const passwordInput = document.getElementById('password');
const passwordError = document.getElementById('password-error');
function validatePassword() {
const password = passwordInput.value;
if (password.length > 0 && password.length < 8) {
passwordInput.setAttribute('aria-invalid', 'true');
passwordError.textContent = 'Password must be at least 8 characters.';
return false;
} else {
passwordInput.removeAttribute('aria-invalid');
passwordError.textContent = '';
return true;
}
}
form.addEventListener('submit', (event) => {
const isPasswordValid = validatePassword();
if (!isPasswordValid) {
event.preventDefault(); // Stop submission
// In a multi-field form, focus the first invalid input
passwordInput.focus();
}
});
// Good UX: validate when the user leaves the field
passwordInput.addEventListener('blur', validatePassword);
</script>
This pattern is the foundation. You can expand it with more validation functions and a loop to check all fields on submit. For complex apps, you'd reach for libraries like Zod or React Hook Form, which manage this for you. Knowing what they do under the hood is what matters.
Handling Server-Side Errors
When your server rejects a submission, it shouldn't just send a generic "Bad Request" error. A good API responds with a 422 Unprocessable Entity or 400 Bad Request status and a JSON body detailing the errors.
A typical error payload looks like this:
{
"errors": [
{
"field": "email",
"message": "An account with this email already exists."
},
{
"field": "username",
"message": "Username must be unique."
}
]
}
Your frontend code should catch this response, parse the JSON, and loop through the errors array. For each error, use the field name to find the corresponding input and display the message using the same accessible pattern you used for client-side validation. This provides a consistent user experience for all types of errors.
Try it
Take the code from the "Practical JavaScript Validation Pattern" section and add a "Confirm Password" field. Implement the logic to check that the two password fields match. Ensure the "Passwords do not match" error is displayed accessibly and that focus is moved to the first password field if they don't match on submission. This should take about 15 minutes.
Next: Multimedia & Embedded Content Accessibility
Lock it in — apply this lesson under interview conditions.