Creating form validation framework
The user wants a custom form validation framework using vanilla JS and CSS, ensuring ARIA compliance. It shouldn’t just be simple—it's meant to be a full framework. I need to consider how to design the architecture, showing modular JS and CSS utilities, as well as usage examples and explanations.
I should provide specific requirements, ensure ARIA compliance with relevant attributes, and include HTML markup examples, all without using any external libraries. This might be a bit of a challenge, but I'm up for it!Developing validation framework with ARIA
I need to provide CSS for styling different states and transitions, along with JavaScript code that defines a ValidationFramework or FormValidator class. This will include the ability to set rules like required fields, patterns, and lengths through a data-validate attribute.
I should integrate with the HTML5 Constraint Validation API, possibly mixing in custom messages. For ARIA compliance, I’ll manage properties like aria-invalid, aria-describedby, and ensure that dynamic updates are appropriately messaged. Plus, we need to check color contrast with CSS for accessibility!Designing API for validation framework
I need to create an API that utilizes a rules object or data attributes like data-validate="required email" and data-minlength="3". As a framework, I should define baseline utilities, starting with a FormValidator class that accepts a form element and optional configurations.
I'll parse the form for any fields marked with [data-validate], and provide default rules such as required, pattern, and min/max length. Each field will have a list of validator functions, and on input or blur events, we'll check the validity of single fields. For form submission, I’ll validate all fields, manage error displays, and update an aria-live region for accessibility.Building a validation framework
I need to ensure we don’t use innerHTML with unsanitized inputs, but static error messages are safe to use. Here’s my plan:
First, I’ll provide a short introduction explaining that we’re creating a small but extensible validation framework. Then, I’ll include an HTML skeleton with a form and attribute-based configuration.
Next, I’ll offer CSS for base styles and ARIA-visible states. Finally, the JavaScript will include a ValidationRules object, a FormValidator class, an initialization script, and comments on customization. I should highlight our use of ARIA attributes, especially regarding screen-reader behavior, and provide separated code snippets for index.html, styles.css, and validation.js.Designing the validation framework
I’m getting into the details now for the validation framework. The API design includes an HTML form with attributes for validation. I’ll initiate JavaScript functionality to ensure each [data-validate] element has an associated error message container.
I need to set ARIA attributes correctly, using aria-invalid for inputs and role="alert" for error summaries. The validation rules cover required fields, email formats, and minimum lengths. For extensibility, I’ll design a FormValidator class that manages event listeners and field validation. I also want to focus on effective error display and accessibility best practices!Refining validation and error handling
To enhance the framework, I’m considering how to conditionally create or remove error elements. Using aria-live="polite" will help with better accessibility without hiding messages. For consistent layout, I plan to use styles like min-height and color coding for errors.
We should set focus on the first invalid field upon submission and ensure proper CSS styling for various states. Registered rules will allow custom validation messages, like for password matches. I’m finalizing the implementation details for the FormValidator class, which will centralize error message management!Designing field validation rules
In getFieldRules, I’m creating a set of rules based on the field’s attributes and data attributes. For example, I'll ensure rules like 'required', 'email', 'minlength', and 'maxlength' are added as needed.
I need to set up specific validation functions for different rules. For instance, the minlength rule will check if the input meets the defined length, while match will compare values between fields. I’ll develop an updateSummary function to compile and display error messages in a user-friendly way, ensuring focus on the first invalid field for better accessibility!Structuring form validation
I need to ensure that the error message area is correctly associated with fields while keeping in mind the grouping limitations, especially for radio buttons. When defining rules, I’ll account for types like ‘required’, ‘email’, and ‘minlength’. For example, I must check if a radio group has any options checked to provide feedback.
Next, I’m structuring the answer with a title and sections for HTML, CSS, and JavaScript. I'll create snippets demonstrating usage, ensuring elements have appropriate ARIA attributes for accessibility. Let's focus on concise code with clear notes for easy integration.Creating form validation logic
I'm working on crafting a JavaScript class called FormValidator that sets up validation rules for form fields. The rules will handle different types, such as required fields, email format, and minlength or maxlength requirements. I need to ensure that error messages display correctly and that users are guided through fixing validation issues. The class will also maintain accessibility standards with ARIA attributes to help assistive technologies convey errors effectively. I’ll organize the code clearly to make it easy for users to implement.Finalizing form validation setup
I'm wrapping up the form validation setup by ensuring various details are in place, like simplifying our methods to avoid using CSS.escape for IDs. Since browser support can vary, I’ll just guarantee that IDs are valid CSS selectors. It should streamline our process while maintaining clarity.
I'll also ensure proper accessibility practices are followed, like using ARIA attributes for error messages. The CSS will handle the layout and styling nicely, including error states and helping users understand what needs fixing. Everything looks organized!Finalizing JavaScript form validation
In the markup, I need to ensure that field.dataset.errorId is defined correctly. My code sets const existingId = field.dataset.errorId || \${field.id}-error`;, which helps find our element for error messages. Settingaria-describedby` will be handled through the JS, so I won't worry about it in the HTML.
Adding novalidate for the form will prevent built-in validation, which is great. I should also consider placing the script at the bottom or linking it externally to keep things tidy. Overall, the goal is to write everything in vanilla JS, CSS, and ARIA-friendly formats for accessibility. Below is a small, extensible validation “framework” in vanilla JS and CSS that is ARIA-aware and accessible.
It gives you:
- Per-field validation rules via
data-validate and standard HTML attributes.
- Inline error messages, linked to inputs with
aria-describedby.
aria-invalid on invalid inputs.
- A form-level error summary with
role="alert" and aria-live.
- A simple API for custom rules.
1. Example HTML
<form id="signup-form" data-validate novalidate>
<!-- Form-level error summary (optional; JS will create one if missing) -->
<div class="form-errors"
data-validation-summary
aria-live="assertive"
role="alert"
tabindex="-1"></div>
<div class="form-field">
<label for="name">Full name <span aria-hidden="true">*</span></label>
<input
id="name"
name="name"
type="text"
required
minlength="2"
data-validate="required minlength"
data-error-required="Please enter your full name."
data-error-minlength="Name must be at least 2 characters long."
/>
<!-- Inline error container (optional; JS will create if missing) -->
<p class="field-error" id="name-error" aria-live="polite"></p>
</div>
<div class="form-field">
<label for="email">Email address <span aria-hidden="true">*</span></label>
<input
id="email"
name="email"
type="email"
required
data-validate="required email"
data-error-required="Email is required."
data-error-email="Enter an email in the format name@example.com."
/>
<p class="field-error" id="email-error" aria-live="polite"></p>
</div>
<div class="form-field">
<label for="password">Password <span aria-hidden="true">*</span></label>
<input
id="password"
name="password"
type="password"
required
minlength="8"
data-validate="required minlength"
data-error-minlength="Password must be at least 8 characters."
/>
<p class="field-error" id="password-error" aria-live="polite"></p>
</div>
<div class="form-field">
<label for="confirm-password">Confirm password <span aria-hidden="true">*</span></label>
<input
id="confirm-password"
name="confirmPassword"
type="password"
required
data-validate="required match"
data-match="#password"
data-error-match="Passwords must match."
/>
<p class="field-error" id="confirm-password-error" aria-live="polite"></p>
</div>
<div class="form-field">
<label>
<input
id="tos"
name="tos"
type="checkbox"
required
data-validate="required"
data-error-required="You must agree to the terms to continue."
/>
I agree to the terms of service
</label>
<p class="field-error" id="tos-error" aria-live="polite"></p>
</div>
<button type="submit">Create account</button>
</form>
Key points:
data-validate marks fields to be validated.
- Optional custom messages via
data-error-<rule> (e.g. data-error-required).
- The script will:
- Ensure each field has an associated
.field-error element.
- Attach
aria-describedby and aria-invalid appropriately.
- Use the summary region with
data-validation-summary (or create one).
2. CSS (styling + focus + error states)
/* Basic layout */
.form-field {
margin-bottom: 1rem;
}
.form-field label {
display: block;
font-weight: 600;
margin-bottom: 0.25rem;
}
/* Inputs */
.form-field input,
.form-field select,
.form-field textarea {
width: 100%;
max-width: 100%;
padding: 0.5rem 0.75rem;
border: 1px solid #ccc;
border-radius: 4px;
font: inherit;
}
.form-field input:focus,
.form-field select:focus,
.form-field textarea:focus {
outline: 2px solid #005fcc;
outline-offset: 2px;
border-color: #005fcc;
}
/* Error state */
.form-field.has-error input,
.form-field.has-error select,
.form-field.has-error textarea {
border-color: #b00020;
}
/* Inline error text */
.field-error {
color: #b00020;
font-size: 0.875rem;
margin-top: 0.25rem;
min-height: 1em; /* reserve space even when empty */
}
/* Form-level summary */
.form-errors {
border: 1px solid #b00020;
background: #fdecea;
color: #b00020;
padding: 0.75rem 1rem;
margin-bottom: 1rem;
border-radius: 4px;
}
.form-errors[hidden] {
display: none;
}
.form-errors ul {
padding-left: 1.25rem;
margin: 0.5rem 0 0;
}
.form-errors a {
color: inherit;
text-decoration: underline;
}
/* Optional visually-hidden utility */
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
border: 0;
clip: rect(0 0 0 0);
}
3. JavaScript framework (vanilla, ARIA-aware)
<script>
class FormValidator {
// Built-in rules: return null when valid, or an error message string when invalid
static rules = {
required(value, field, form) {
// Checkboxes
if (field.type === 'checkbox') {
return field.checked ? null : 'This field is required.';
}
// Radio groups (check at least one in the group)
if (field.type === 'radio') {
if (!field.name) return field.checked ? null : 'This field is required.';
const group = form.querySelectorAll(
'input[type="radio"][name="' + field.name + '"]'
);
const checked = Array.from(group).some(input => input.checked);
return checked ? null : 'Please select an option.';
}
// Everything else
return value.trim() === '' ? 'This field is required.' : null;
},
email(value) {
const trimmed = value.trim();
if (trimmed === '') return null; // Let "required" handle empties
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(trimmed) ? null : 'Please enter a valid email address.';
},
minlength(value, field) {
const min = parseInt(
field.getAttribute('minlength') || field.dataset.minlength,
10
);
if (!min || value === '') return null;
return value.length < min
? `Please enter at least ${min} characters.`
: null;
},
maxlength(value, field) {
const max = parseInt(
field.getAttribute('maxlength') || field.dataset.maxlength,
10
);
if (!max || value === '') return null;
return value.length > max
? `Please enter no more than ${max} characters.`
: null;
},
pattern(value, field) {
const pattern = field.getAttribute('pattern') || field.dataset.pattern;
if (!pattern || value === '') return null;
const re = new RegExp(pattern);
return re.test(value) ? null : 'Please match the requested format.';
},
match(value, field, form) {
const selector = field.dataset.match;
if (!selector || value === '') return null;
const other = form.querySelector(selector);
if (!other) return null;
return value === other.value ? null : 'Values do not match.';
}
};
// Allow custom rules to be registered: FormValidator.registerRule('myRule', fn)
static registerRule(name, fn) {
this.rules[name] = fn;
}
constructor(form, options = {}) {
this.form = form;
this.options = Object.assign(
{
showErrorsOn: 'blur' // 'blur' | 'input'
},
options
);
this.fields = Array.from(this.form.querySelectorAll('[data-validate]'));
this.errorEls = new Map();
this.summaryEl = this.ensureSummaryElement();
this.setupFields();
this.attachEvents();
}
ensureSummaryElement() {
let el = this.form.querySelector('[data-validation-summary]');
if (!el) {
el = document.createElement('div');
el.className = 'form-errors';
el.setAttribute('data-validation-summary', '');
el.setAttribute('aria-live', 'assertive');
el.setAttribute('role', 'alert');
el.setAttribute('tabindex', '-1');
this.form.insertBefore(el, this.form.firstChild);
}
el.hidden = true;
return el;
}
setupFields() {
this.fields.forEach(field => {
// Ensure each field has an id so labels and error messages can refer to it
if (!field.id) {
field.id =
(field.name || 'field') +
'-' +
Math.random().toString(36).slice(2, 8);
}
const errorEl = this.ensureErrorElement(field);
this.errorEls.set(field, errorEl);
});
}
ensureErrorElement(field) {
const proposedId = field.dataset.errorId || `${field.id}-error`;
let errorEl = this.form.querySelector('#' + proposedId);
if (!errorEl) {
errorEl = document.createElement('p');
errorEl.className = 'field-error';
errorEl.id = proposedId;
errorEl.setAttribute('aria-live', 'polite');
field.insertAdjacentElement('afterend', errorEl);
}
field.dataset.errorId = errorEl.id;
// Link via aria-describedby (preserve any existing ids)
const describedBy = field.getAttribute('aria-describedby') || '';
const ids = new Set(
describedBy
.split(/\s+/)
.concat(errorEl.id)
.filter(Boolean)
);
field.setAttribute('aria-describedby', Array.from(ids).join(' '));
return errorEl;
}
attachEvents() {
this.form.addEventListener('submit', e => {
const isValid = this.validateForm();
if (!isValid) {
e.preventDefault();
}
});
this.fields.forEach(field => {
if (this.options.showErrorsOn === 'input') {
field.addEventListener('input', () => this.validateField(field));
field.addEventListener('blur', () => this.validateField(field));
} else if (this.options.showErrorsOn === 'blur') {
field.addEventListener('blur', () => this.validateField(field));
}
});
}
getFieldRules(field) {
const rules = new Set();
// Explicit rules via data-validate
const explicit = (field.dataset.validate || '')
.split(/\s+/)
.map(r => r.trim())
.filter(Boolean);
explicit.forEach(r => rules.add(r.toLowerCase()));
// Infer some rules from native attributes
if (field.required) rules.add('required');
if (field.type === 'email') rules.add('email');
if (field.hasAttribute('minlength') || field.dataset.minlength) {
rules.add('minlength');
}
if (field.hasAttribute('maxlength') || field.dataset.maxlength) {
rules.add('maxlength');
}
if (field.hasAttribute('pattern') || field.dataset.pattern) {
rules.add('pattern');
}
if (field.dataset.match) rules.add('match');
return Array.from(rules);
}
getOverrideMessage(field, ruleName) {
// data-error-required -> dataset.errorRequired
const key = 'error' + ruleName.charAt(0).toUpperCase() + ruleName.slice(1);
return field.dataset[key] || null;
}
validateField(field) {
const rules = this.getFieldRules(field);
if (!rules.length) return true;
const value = field.value;
let errorMessage = null;
for (const ruleName of rules) {
const ruleFn = FormValidator.rules[ruleName];
if (!ruleFn) continue;
const result = ruleFn(value, field, this.form);
if (typeof result === 'string' && result) {
errorMessage = this.getOverrideMessage(field, ruleName) || result;
break;
}
}
if (errorMessage) {
this.showFieldError(field, errorMessage);
return false;
} else {
this.clearFieldError(field);
return true;
}
}
showFieldError(field, message) {
const errorEl = this.errorEls.get(field);
if (!errorEl) return;
errorEl.textContent = message;
field.setAttribute('aria-invalid', 'true');
field.classList.add('is-invalid');
const wrapper = field.closest('.form-field');
if (wrapper) wrapper.classList.add('has-error');
}
clearFieldError(field) {
const errorEl = this.errorEls.get(field);
if (!errorEl) return;
errorEl.textContent = '';
field.removeAttribute('aria-invalid');
field.classList.remove('is-invalid');
const wrapper = field.closest('.form-field');
if (wrapper) wrapper.classList.remove('has-error');
}
validateForm() {
let firstInvalidField = null;
this.fields.forEach(field => {
const valid = this.validateField(field);
if (!valid && !firstInvalidField) {
firstInvalidField = field;
}
});
if (firstInvalidField) {
this.renderSummary();
// Focus first invalid field for keyboard and screen-reader users
firstInvalidField.focus();
firstInvalidField.scrollIntoView({ behavior: 'smooth', block: 'center' });
return false;
} else {
this.clearSummary();
return true;
}
}
getFieldLabel(field) {
const id = field.id;
if (!id) return field.name || '';
const label = this.form.querySelector('label[for="' + id + '"]');
return label ? label.textContent.trim() : field.name || '';
}
renderSummary() {
if (!this.summaryEl) return;
const items = [];
this.fields.forEach(field => {
const errorEl = this.errorEls.get(field);
if (errorEl && errorEl.textContent.trim()) {
items.push({
label: this.getFieldLabel(field),
message: errorEl.textContent.trim(),
fieldId: field.id
});
}
});
if (!items.length) {
this.clearSummary();
return;
}
const list = document.createElement('ul');
items.forEach(item => {
const li = document.createElement('li');
const link = document.createElement('a');
link.href = '#' + item.fieldId;
link.textContent = `${item.label}: ${item.message}`;
link.addEventListener('click', e => {
e.preventDefault();
const target = this.form.querySelector('#' + item.fieldId);
if (target) {
target.focus();
}
});
li.appendChild(link);
list.appendChild(li);
});
this.summaryEl.innerHTML = '';
const intro = document.createElement('p');
intro.textContent = 'There were problems with your submission:';
this.summaryEl.appendChild(intro);
this.summaryEl.appendChild(list);
this.summaryEl.hidden = false;
}
clearSummary() {
if (!this.summaryEl) return;
this.summaryEl.innerHTML = '';
this.summaryEl.hidden = true;
}
}
// Auto-initialize all forms that have data-validate
document.addEventListener('DOMContentLoaded', () => {
document
.querySelectorAll('form[data-validate]')
.forEach(form => new FormValidator(form));
});
</script>
4. Adding custom validation rules
You can extend the framework with your own rules:
FormValidator.registerRule('username', (value, field) => {
if (!value) return null; // let "required" handle empties
const ok = /^[a-z0-9_]+$/i.test(value);
return ok
? null
: 'Usernames may contain only letters, numbers, and underscores.';
});
Then in HTML:
<input
id="username"
name="username"
type="text"
required
data-validate="required username"
data-error-username="Choose a username with only letters, numbers, and underscores."
/>
<p class="field-error" id="username-error" aria-live="polite"></p>
The ARIA aspects (inline aria-live regions, aria-invalid, error summary role="alert", aria-describedby linking) are handled for you, so you can focus on writing rules and styling.