I'm focused on the project's parameters now. The core goal, building a form validation framework with vanilla JS and CSS while adhering to ARIA standards, is clear. Zero dependencies is a hard constraint. My next step will be breaking down the requirements into actionable steps.
Mapping Out Implementation Steps
I'm now detailing the steps to make this happen. First, HTML and CSS will be built with the framework's features in mind. I'll need a way to link the inputs with their errors. Then, a JavaScript core will manage selections, validation routines, and the updating of the DOM to show those errors.
Planning the Framework's Structure
I'm solidifying the structure now. HTML will use data attributes for validation rules. CSS handles visual feedback, error visibility, and styling. The core JS will handle selection, validation based on those data attributes, and DOM manipulation for updates, ARIA attributes, and feedback.
Designing the Core Functionality
I'm now crafting the core JavaScript logic. A modular pattern is taking shape. I'll need a set of validation functions, a central validateField method to apply them based on data attributes, and methods for DOM manipulation to handle feedback and ARIA attributes. I'm also considering how the form's submit event will be handled.
Defining Validation Rules & Logic
Now, I'm defining the validation rules. I'll need a set of functions for required, email, and other common checks, likely stored in an object. I'll be using a hybrid approach, leveraging HTML5 attributes like required and type="email" for configuration, but overriding browser validation to control the visual feedback and ARIA attributes via Javascript. The validateField method is the core.
Structuring the Implementation Plan
I'm now consolidating the steps. I've decided to use a class-based structure for the core Javascript framework, encompassing initialization, validation rules, and DOM manipulation methods. The data-validate attribute will be the primary source for configuration, while still respecting HTML5 attributes like minlength. I'm also considering the balance between real-time and submit validation.
Developing the Core Framework
I am now actively translating the plan into code. I'm building a class, FormValidator, with methods for input selection, validation based on data-validate rules, and the application of feedback. I'm focusing on the validateField method to handle input types, CSS class toggling, and ARIA attribute updates. I will ensure complete ARIA compliance.
This is a complete solution for a lightweight, extensible, and fully accessible form validation framework using only vanilla JavaScript and CSS.
The Architecture
HTML: Uses standard semantic tags. We disable default browser validation (novalidate) but utilize standard attributes (like required, pattern, minlength) which our JavaScript will read.
CSS: Handles visual states (.error, .success) and hides/shows error messages.
JavaScript:
ARIA Management: Dynamically toggles aria-invalid and links inputs to error messages using aria-describedby.
Event Delegation: Listens for blur (validation trigger) and input (real-time correction).
Extensibility: Easy to add new regex rules.
1. The CSS (Styles)
Save this as styles.css or inside a <style> block. Note the use of CSS variables for easy theming.
This script effectively "hijacks" the HTML5 validation attributes to provide a custom UI while maintaining semantic meaning.
javascript
3. The HTML Implementation
Here is how you construct your form. Note the data-error-... attributes which allow you to customize execution messages directly in the HTML without touching the JS.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Accessible Form Validator</title>
<!-- Link to CSS file here -->
</head>
<body>
<div style="max-width: 500px; margin: 2rem auto; font-family: sans-serif;">
<h1>Registration</h1>
<form id="myForm">
<!-- Name Field -->
<div class="form-group">
<label for="username">Username <span aria-hidden="true">*</span></label>
<input
type="text"
id="username"
name="username"
class="form-control"
required
minlength="3"
data-error-required="Username is required."
>
<!--
ARIA Live Region:
role="alert" or aria-live="polite" ensures screen readers announce
the error when it becomes visible.
-->
<span class="error-message" aria-live="polite"></span>
</div>
<!-- Email Field -->
<div class="form-group">
<label for="email">Email Address <span aria-hidden="true">*</span></label>
<input
type="email"
id="email"
name="email"
class="form-control"
required
data-error-email="Please enter a valid email (e.g., user@domain.com)"
>
<span class="error-message" aria-live="polite"></span>
</div>
<!-- Custom Pattern Field (e.g. US Zip Code) -->
<div class="form-group">
<label for="zipcode">Zip Code</label>
<input
type="text"
id="zipcode"
name="zipcode"
class="form-control"
pattern="^\d{5}$"
data-error-pattern="Zip code must be exactly 5 digits."
>
<span class="error-message" aria-live="polite"></span>
</div>
<button type="submit" style="padding: 10px 20px; background: #1a73e8; color: white; border: none; border-radius: 4px; cursor: pointer;">
Register
</button>
</form>
</div>
<!-- Link to JS file here -->
</body>
</html>
Key ARIA Features Explained
aria-invalid="true":
When validation fails, JS adds this attribute to the <input>. Screen readers will announce "Invalid" along with the field name.
aria-describedby="fieldID-error":
When an error occurs, JS generates an ID for the error message container (if missing) and links the input to it.
When a user focuses the input, the screen reader will read the label plus the text inside the error message.
aria-live="polite":
Placed on the .error-message span. If an error appears while the user is still focused on the page (e.g., onblur), the screen reader will politely announce the error text without aggressively interrupting the user's current flow.
Focus Management:
The focusFirstError() method ensures that if a user hits submit and there are errors, keyboard focus is immediately moved to the first invalid field so the user isn't lost.
How to Extend
If you want to add a password matching rule, simply update the rules object in the constructor and the validateField method:
Update rules: match: (value, compareId) => value === document.getElementById(compareId).value
Add a data-match="id_of_other_field" to your HTML input.
Update validateField logic to check for that attribute.
class FormValidator {
constructor(formSelector) {
this.form = document.querySelector(formSelector);
if (!this.form) return;
// Disable default HTML5 validation bubbles
this.form.setAttribute('novalidate', true);
// Store rules
this.rules = {
required: (value) => value.trim() !== '',
email: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
minlength: (value, min) => value.length >= min,
pattern: (value, pattern) => new RegExp(pattern).test(value)
};
this.init();
}
init() {
// Validate on Blur (when user leaves field)
this.form.addEventListener('blur', (e) => {
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
this.validateField(e.target);
}
}, true);
// Clear error on Input (as user types correction)
this.form.addEventListener('input', (e) => {
if (e.target.classList.contains('has-error')) {
this.validateField(e.target);
}
});
// Validate entire form on Submit
this.form.addEventListener('submit', (e) => {
e.preventDefault();
const isValid = this.validateAll();
if (isValid) {
// Simulate submission or actually submit
console.log('Form is valid! Submitting...');
// this.form.submit(); // Uncomment to allow actual submission
alert('Success! Form submitted.');
} else {
this.focusFirstError();
}
});
}
validateField(input) {
const errors = [];
const value = input.value;
// 1. Check Required
if (input.hasAttribute('required') && !this.rules.required(value)) {
errors.push(input.dataset.errorRequired || 'This field is required.');
}
// Only check other rules if field is not empty
else if (value !== '') {
// 2. Check Type Email
if (input.type === 'email' && !this.rules.email(value)) {
errors.push(input.dataset.errorEmail || 'Please enter a valid email address.');
}
// 3. Check MinLength
if (input.hasAttribute('minlength')) {
const min = parseInt(input.getAttribute('minlength'));
if (!this.rules.minlength(value, min)) {
errors.push(`Must be at least ${min} characters.`);
}
}
// 4. Check Custom Pattern
if (input.hasAttribute('pattern') && !this.rules.pattern(value, input.getAttribute('pattern'))) {
errors.push(input.dataset.errorPattern || 'Invalid format.');
}
}
// Toggle State
if (errors.length > 0) {
this.showError(input, errors[0]);
return false;
} else {
this.clearError(input);
return true;
}
}
showError(input, message) {
const container = input.closest('.form-group');
const errorDisplay = container.querySelector('.error-message');
// Visuals
input.classList.add('has-error');
input.classList.remove('has-success');
// ARIA: Mark invalid
input.setAttribute('aria-invalid', 'true');
// Update Error Message
if (errorDisplay) {
errorDisplay.textContent = message;
errorDisplay.classList.add('is-visible');
// ARIA: Link input to error message ID
// Ensure error span has an ID
if (!errorDisplay.id) {
errorDisplay.id = `${input.id}-error`;
}
input.setAttribute('aria-describedby', errorDisplay.id);
}
}
clearError(input) {
const container = input.closest('.form-group');
const errorDisplay = container.querySelector('.error-message');
// Visuals
input.classList.remove('has-error');
input.classList.add('has-success');
// ARIA: Mark valid
input.setAttribute('aria-invalid', 'false');
input.removeAttribute('aria-describedby');
// Hide Message
if (errorDisplay) {
errorDisplay.classList.remove('is-visible');
errorDisplay.textContent = '';
}
}
validateAll() {
const inputs = this.form.querySelectorAll('input, textarea, select');
let isFormValid = true;
inputs.forEach(input => {
const isFieldValid = this.validateField(input);
if (!isFieldValid) isFormValid = false;
});
return isFormValid;
}
focusFirstError() {
const firstError = this.form.querySelector('.has-error');
if (firstError) {
firstError.focus();
}
}
}
// Initialize
document.addEventListener('DOMContentLoaded', () => {
new FormValidator('#myForm');
});