Next.js course ยท Module 6: Forms and Server Actions
Usability and accessibility in forms
In this lesson7
Designing forms that are both user-friendly (usability) and accessible to people with various disabilities (accessibility) is a key aspect of building modern web applications. In this module we'll discuss how to create forms that are easy to use for all users, regardless of their abilities and the devices they use.
Why are usability and accessibility important?
Business benefits
- Increased conversion - forms that are easy to use have higher conversion rates
- Wider reach - accessible forms reach more users
- Legal compliance - in many countries website accessibility is required by law (e.g., ADA in the US, WCAG in the EU)
- Improved SEO - accessible pages often rank better in search results
Benefits for users
- Better performance - users can fill out forms faster and more easily
- Less frustration - well-designed forms reduce errors and frustration
- Greater independence - people with disabilities can use forms on their own
- Consistent experience - well-designed forms work consistently across various devices and browsers
Basic principles of form usability
1. Clear structure
- Group related fields - use
<fieldset>and<legend>to group fields - Logical order - organize fields in an intuitive order
- Appropriate labels - each field should have a clear label
2. Minimize cognitive load
- Ask only for necessary information - every additional field reduces conversion
- Break long forms into steps - multi-step forms are easier to process
- Show progress - in multi-step forms, inform the user of progress
3. Clear communication
- Clearly marked required fields - mark required fields consistently and visibly
- Precise labels - labels should clearly communicate what information is expected
- Hints and examples - for complex fields, add examples or hints
4. Effective data submission
- Real-time validation - inform about errors while filling out the form
- Preserve data on errors - don't reset the entire form after an error occurs
- Confirm actions - inform the user of the success or failure of form submission
Form accessibility principles
1. HTML structural principles
- Correctly associate labels with fields - use
<label for="id">linked to the field'sid - Group fields - use
<fieldset>and<legend>for groups of fields, especially checkboxes and radio buttons - Logical tab order - ensure the tab order is logical and intuitive
2. ARIA (Accessible Rich Internet Applications)
- aria-label and aria-labelledby attributes - for describing elements without visible labels
- aria-describedby - for linking additional descriptions with fields
- aria-required - for marking required fields
- aria-invalid - for marking fields with errors
- role="alert" - for error messages that should be read immediately
3. Contrast and readability
- Sufficient contrast - the contrast ratio between text and background should be at least 4.5:1
- Appropriate text size - text should be readable without zooming in
- Responsive design - forms should be usable on various screen sizes
4. Keyboard support
- Full keyboard support - all functions should be accessible via keyboard
- Visible focus - keyboard focus should be clearly visible
- Keyboard shortcuts - for advanced forms, keyboard shortcuts can be added
Implementing accessible forms in React
Basic accessible form
import { useState, FormEvent, ChangeEvent } from 'react';
export default function AccessibleForm() {
const [formData, setFormData] = useState({
name: '',
email: '',
phone: '',
message: '',
contactPreference: 'email',
newsletter: false
});
const [errors, setErrors] = useState<Record<string, string>>({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const handleChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
const { name, value, type } = e.target;
const checked = type === 'checkbox' ? (e.target as HTMLInputElement).checked : undefined;
setFormData(prev => ({
...prev,
[name]: checked !== undefined ? checked : value
}));
// Remove error after editing the field
if (errors[name]) {
setErrors(prev => {
const newErrors = { ...prev };
delete newErrors[name];
return newErrors;
});
}
};
const validateForm = () => {
const newErrors: Record<string, string> = {};
if (!formData.name.trim()) {
newErrors.name = 'Full name is required';
}
if (!formData.email.trim()) {
newErrors.email = 'Email is required';
} else if (!/^\S+@\S+\.\S+$/.test(formData.email)) {
newErrors.email = 'Please provide a valid email address';
}
if (formData.contactPreference === 'phone' && !formData.phone.trim()) {
newErrors.phone = 'Phone number is required when choosing phone contact';
}
if (!formData.message.trim()) {
newErrors.message = 'Message is required';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!validateForm()) {
// Move focus to the first field with an error
const firstErrorField = document.getElementById(Object.keys(errors)[0]);
if (firstErrorField) {
firstErrorField.focus();
}
return;
}
setIsSubmitting(true);
try {
// Simulate form submission
await new Promise(resolve => setTimeout(resolve, 1500));
console.log('Form sent:', formData);
setIsSuccess(true);
// Move focus to the success message
const successMessage = document.getElementById('success-message');
if (successMessage) {
successMessage.focus();
}
// Reset form
setFormData({
name: '',
email: '',
phone: '',
message: '',
contactPreference: 'email',
newsletter: false
});
} catch (error) {
setErrors({
form: 'An error occurred while sending the form. Please try again later.'
});
// Move focus to the error message
const errorMessage = document.getElementById('form-error');
if (errorMessage) {
errorMessage.focus();
}
} finally {
setIsSubmitting(false);
}
};
return (
<div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-md">
<h1 className="text-2xl font-bold mb-6">Contact us</h1>
{isSuccess && (
<div
id="success-message"
className="mb-4 p-3 bg-green-100 border border-green-400 text-green-700 rounded"
role="alert"
tabIndex={-1} // Allows the element to receive focus
>
Thank you for submitting the form! We'll respond as soon as possible.
</div>
)}
{errors.form && (
<div
id="form-error"
className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded"
role="alert"
tabIndex={-1} // Allows the element to receive focus
>
{errors.form}
</div>
)}
<form onSubmit={handleSubmit} noValidate className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-700">
Full name <span className="text-red-500" aria-hidden="true">*</span>
</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
aria-required="true"
aria-invalid={Boolean(errors.name)}
aria-describedby={errors.name ? 'name-error' : undefined}
className={`mt-1 block w-full rounded-md shadow-sm ${errors.name ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.name && (
<p id="name-error" className="mt-1 text-sm text-red-600" role="alert">
{errors.name}
</p>
)}
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700">
Email <span className="text-red-500" aria-hidden="true">*</span>
</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
aria-required="true"
aria-invalid={Boolean(errors.email)}
aria-describedby={errors.email ? 'email-error' : undefined}
className={`mt-1 block w-full rounded-md shadow-sm ${errors.email ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.email && (
<p id="email-error" className="mt-1 text-sm text-red-600" role="alert">
{errors.email}
</p>
)}
</div>
<fieldset>
<legend className="text-sm font-medium text-gray-700">Preferred contact method</legend>
<div className="mt-2 space-y-2">
<div className="flex items-center">
<input
type="radio"
id="email-contact"
name="contactPreference"
value="email"
checked={formData.contactPreference === 'email'}
onChange={handleChange}
className="h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500"
/>
<label htmlFor="email-contact" className="ml-2 block text-sm text-gray-700">
Email
</label>
</div>
<div className="flex items-center">
<input
type="radio"
id="phone-contact"
name="contactPreference"
value="phone"
checked={formData.contactPreference === 'phone'}
onChange={handleChange}
className="h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500"
/>
<label htmlFor="phone-contact" className="ml-2 block text-sm text-gray-700">
Phone
</label>
</div>
</div>
</fieldset>
<div className={formData.contactPreference === 'phone' ? 'block' : 'hidden'}>
<label htmlFor="phone" className="block text-sm font-medium text-gray-700">
Phone number {formData.contactPreference === 'phone' && <span className="text-red-500" aria-hidden="true">*</span>}
</label>
<input
type="tel"
id="phone"
name="phone"
value={formData.phone}
onChange={handleChange}
aria-required={formData.contactPreference === 'phone'}
aria-invalid={Boolean(errors.phone)}
aria-describedby={errors.phone ? 'phone-error' : 'phone-hint'}
className={`mt-1 block w-full rounded-md shadow-sm ${errors.phone ? 'border-red-500' : 'border-gray-300'}`}
/>
<p id="phone-hint" className="mt-1 text-xs text-gray-500">
Format: 123-456-789
</p>
{errors.phone && (
<p id="phone-error" className="mt-1 text-sm text-red-600" role="alert">
{errors.phone}
</p>
)}
</div>
<div>
<label htmlFor="message" className="block text-sm font-medium text-gray-700">
Message <span className="text-red-500" aria-hidden="true">*</span>
</label>
<textarea
id="message"
name="message"
rows={4}
value={formData.message}
onChange={handleChange}
aria-required="true"
aria-invalid={Boolean(errors.message)}
aria-describedby={errors.message ? 'message-error' : undefined}
className={`mt-1 block w-full rounded-md shadow-sm ${errors.message ? 'border-red-500' : 'border-gray-300'}`}
/>
{errors.message && (
<p id="message-error" className="mt-1 text-sm text-red-600" role="alert">
{errors.message}
</p>
)}
</div>
<div className="flex items-center">
<input
type="checkbox"
id="newsletter"
name="newsletter"
checked={formData.newsletter}
onChange={handleChange}
className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
/>
<label htmlFor="newsletter" className="ml-2 block text-sm text-gray-700">
Sign me up for the newsletter
</label>
</div>
<div className="pt-2">
<p className="text-xs text-gray-500">
Fields marked with <span className="text-red-500" aria-hidden="true">*</span> are required
</p>
</div>
<button
type="submit"
disabled={isSubmitting}
aria-disabled={isSubmitting}
className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
>
{isSubmitting ? 'Sending...' : 'Send message'}
</button>
</form>
</div>
);
}Key accessibility elements in the above example:
- Correctly associated labels with fields - each label has an
htmlForattribute linked to the field'sid - Grouping with fieldset and legend - for radio buttons
- ARIA attributes -
aria-required,aria-invalid,aria-describedby - Dynamic visibility - the phone field appears only when needed
- Error messages with role="alert" - for screen readers
- Focus management - moving focus to the first error or the success message
Advanced practices for accessible forms
1. Focus management
Proper focus management is crucial for keyboard users and screen readers:
import { useRef, useEffect } from 'react';
function FocusManagementExample() {
const firstInputRef = useRef<HTMLInputElement>(null);
const errorMessageRef = useRef<HTMLDivElement>(null);
const successMessageRef = useRef<HTMLDivElement>(null);
// Autofocus on the first form field on mount
useEffect(() => {
if (firstInputRef.current) {
firstInputRef.current.focus();
}
}, []);
// Example function to move focus to the first error
const moveToFirstError = () => {
if (errorMessageRef.current) {
errorMessageRef.current.focus();
errorMessageRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
};
// Example function to move focus to the success message
const moveToSuccessMessage = () => {
if (successMessageRef.current) {
successMessageRef.current.focus();
successMessageRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
};
return (
<form>
{/* Error message with ability to receive focus */}
<div
ref={errorMessageRef}
tabIndex={-1}
role="alert"
className="bg-red-100 p-3 rounded"
style={{ display: 'none' }} // Normally controlled by state
>
Errors occurred in the form
</div>
{/* First form field */}
<div>
<label htmlFor="first-field">First name</label>
<input
ref={firstInputRef}
id="first-field"
type="text"
/>
</div>
{/* Success message */}
<div
ref={successMessageRef}
tabIndex={-1}
role="status"
className="bg-green-100 p-3 rounded"
style={{ display: 'none' }} // Normally controlled by state
>
The form was sent successfully!
</div>
{/* Buttons to demonstrate focus movement */}
<div className="mt-4 space-x-2">
<button type="button" onClick={moveToFirstError}>
Show error
</button>
<button type="button" onClick={moveToSuccessMessage}>
Show success
</button>
</div>
</form>
);
}2. Autocomplete fields
Well-implemented autocomplete fields can significantly improve form usability:
import { useState, useRef, KeyboardEvent } from 'react';
interface Props {
suggestions: string[];
label: string;
id: string;
value: string;
onChange: (value: string) => void;
}
function AccessibleAutocomplete({ suggestions, label, id, value, onChange }: Props) {
const [filteredSuggestions, setFilteredSuggestions] = useState<string[]>([]);
const [showSuggestions, setShowSuggestions] = useState(false);
const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(0);
const suggestionsListRef = useRef<HTMLUListElement>(null);
// Filter suggestions based on current input
const filterSuggestions = (input: string) => {
const filtered = suggestions.filter(suggestion =>
suggestion.toLowerCase().includes(input.toLowerCase())
);
setFilteredSuggestions(filtered);
setShowSuggestions(true);
setActiveSuggestionIndex(0);
};
// Handle value change
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const userInput = e.target.value;
onChange(userInput);
filterSuggestions(userInput);
};
// Handle suggestion click
const handleSuggestionClick = (suggestion: string) => {
onChange(suggestion);
setShowSuggestions(false);
setActiveSuggestionIndex(0);
};
// Handle keyboard navigation
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
// Arrow down - move to next suggestion
if (e.key === 'ArrowDown') {
e.preventDefault();
setActiveSuggestionIndex(prev =>
prev < filteredSuggestions.length - 1 ? prev + 1 : prev
);
}
// Arrow up - move to previous suggestion
else if (e.key === 'ArrowUp') {
e.preventDefault();
setActiveSuggestionIndex(prev => (prev > 0 ? prev - 1 : 0));
}
// Enter - select active suggestion
else if (e.key === 'Enter' && showSuggestions) {
e.preventDefault();
if (filteredSuggestions[activeSuggestionIndex]) {
handleSuggestionClick(filteredSuggestions[activeSuggestionIndex]);
}
}
// Escape - close suggestions list
else if (e.key === 'Escape') {
setShowSuggestions(false);
}
};
// ID for the suggestions list (to link with ARIA)
const listId = `${id}-suggestions`;
return (
<div className="relative">
<label htmlFor={id} className="block text-sm font-medium text-gray-700">
{label}
</label>
<input
type="text"
id={id}
value={value}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onFocus={() => filterSuggestions(value)}
onBlur={() => {
// Delay to allow suggestion click
setTimeout(() => setShowSuggestions(false), 200);
}}
aria-autocomplete="list"
aria-controls={listId}
aria-activedescendant={
showSuggestions && filteredSuggestions.length > 0
? `${id}-suggestion-${activeSuggestionIndex}`
: undefined
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
/>
{/* Suggestions list */}
{showSuggestions && filteredSuggestions.length > 0 && (
<ul
id={listId}
ref={suggestionsListRef}
role="listbox"
className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5"
>
{filteredSuggestions.map((suggestion, index) => (
<li
key={index}
id={`${id}-suggestion-${index}`}
role="option"
aria-selected={index === activeSuggestionIndex}
onClick={() => handleSuggestionClick(suggestion)}
className={`cursor-default select-none relative py-2 px-4 ${index === activeSuggestionIndex ? 'bg-blue-100' : ''}`}
>
{suggestion}
</li>
))}
</ul>
)}
</div>
);
}Key accessibility elements in autocomplete:
- ARIA roles -
aria-autocomplete="list",role="listbox",role="option" - aria-activedescendant - to mark the active suggestion
- aria-controls - links the field with the suggestions list
- Keyboard support - arrows, Enter, Escape
3. Date pickers and masked inputs
Date fields and other complex inputs should be accessible and easy to use:
import { useState, useRef, ChangeEvent } from 'react';
function AccessibleDateInput() {
const [date, setDate] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
// Format date in DD-MM-YYYY format
const formatDate = (input: string) => {
// Remove all non-digit characters
const digitsOnly = input.replace(/\D/g, '');
// Add dashes in the appropriate places
let formatted = '';
for (let i = 0; i < digitsOnly.length && i < 8; i++) {
if (i === 2 || i === 4) formatted += '-';
formatted += digitsOnly[i];
}
return formatted;
};
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const input = e.target.value;
const formatted = formatDate(input);
setDate(formatted);
// Preserve the cursor position after formatting
if (inputRef.current) {
const cursorPosition = e.target.selectionStart || 0;
const diffLength = formatted.length - input.length;
setTimeout(() => {
inputRef.current?.setSelectionRange(cursorPosition + diffLength, cursorPosition + diffLength);
}, 0);
}
};
// Date validation
const validateDate = (date: string) => {
// Check DD-MM-YYYY format
if (!/^\d{2}-\d{2}-\d{4}$/.test(date)) return false;
const [day, month, year] = date.split('-').map(Number);
// Check month range
if (month < 1 || month > 12) return false;
// Check number of days in the month
const daysInMonth = new Date(year, month, 0).getDate();
if (day < 1 || day > daysInMonth) return false;
return true;
};
// Generate instructions for screen readers
const dateInstructions = 'Enter the date in DD-MM-YYYY format, for example 01-06-2023 for June 1, 2023.';
return (
<div>
<label htmlFor="date-input" className="block text-sm font-medium text-gray-700">
Date
</label>
<input
ref={inputRef}
type="text"
id="date-input"
value={date}
onChange={handleChange}
aria-describedby="date-instructions"
aria-invalid={date !== '' && !validateDate(date)}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm"
/>
<p id="date-instructions" className="mt-1 text-xs text-gray-500">
{dateInstructions}
</p>
{date !== '' && !validateDate(date) && (
<p className="mt-1 text-sm text-red-600" role="alert">
The entered date is invalid. {dateInstructions}
</p>
)}
</div>
);
}4. Reusable accessible form components
Creating a library of reusable, accessible form components can significantly simplify building consistent and accessible forms across the entire application:
// components/FormElements.tsx
import { InputHTMLAttributes, TextareaHTMLAttributes, ReactNode } from 'react';
// Label component
interface LabelProps {
htmlFor: string;
children: ReactNode;
required?: boolean;
}
export function FormLabel({ htmlFor, children, required }: LabelProps) {
return (
<label htmlFor={htmlFor} className="block text-sm font-medium text-gray-700">
{children}
{required && <span className="text-red-500 ml-1" aria-hidden="true">*</span>}
</label>
);
}
// Text input component
interface TextInputProps extends InputHTMLAttributes<HTMLInputElement> {
id: string;
label: string;
error?: string;
hint?: string;
required?: boolean;
}
export function TextInput({
id,
label,
error,
hint,
required,
...props
}: TextInputProps) {
const errorId = error ? `${id}-error` : undefined;
const hintId = hint ? `${id}-hint` : undefined;
const describedBy = [errorId, hintId].filter(Boolean).join(' ') || undefined;
return (
<div className="mb-4">
<FormLabel htmlFor={id} required={required}>{label}</FormLabel>
<input
id={id}
type="text"
aria-invalid={Boolean(error)}
aria-required={required}
aria-describedby={describedBy}
className={`mt-1 block w-full rounded-md ${error ? 'border-red-500' : 'border-gray-300'}`}
{...props}
/>
{hint && !error && (
<p id={hintId} className="mt-1 text-xs text-gray-500">
{hint}
</p>
)}
{error && (
<p id={errorId} className="mt-1 text-sm text-red-600" role="alert">
{error}
</p>
)}
</div>
);
}
// Multi-line text input component
interface TextareaProps extends TextareaHTMLAttributes<HTMLTextAreaElement> {
id: string;
label: string;
error?: string;
hint?: string;
required?: boolean;
}
export function Textarea({
id,
label,
error,
hint,
required,
...props
}: TextareaProps) {
const errorId = error ? `${id}-error` : undefined;
const hintId = hint ? `${id}-hint` : undefined;
const describedBy = [errorId, hintId].filter(Boolean).join(' ') || undefined;
return (
<div className="mb-4">
<FormLabel htmlFor={id} required={required}>{label}</FormLabel>
<textarea
id={id}
aria-invalid={Boolean(error)}
aria-required={required}
aria-describedby={describedBy}
className={`mt-1 block w-full rounded-md ${error ? 'border-red-500' : 'border-gray-300'}`}
{...props}
/>
{hint && !error && (
<p id={hintId} className="mt-1 text-xs text-gray-500">
{hint}
</p>
)}
{error && (
<p id={errorId} className="mt-1 text-sm text-red-600" role="alert">
{error}
</p>
)}
</div>
);
}
// Radio or checkbox group component
interface OptionItem {
id: string;
value: string;
label: string;
}
interface CheckboxOrRadioGroupProps {
legend: string;
name: string;
options: OptionItem[];
type: 'checkbox' | 'radio';
values: string[];
onChange: (value: string, checked: boolean) => void;
error?: string;
required?: boolean;
}
export function OptionGroup({
legend,
name,
options,
type,
values,
onChange,
error,
required
}: CheckboxOrRadioGroupProps) {
const errorId = error ? `${name}-error` : undefined;
return (
<fieldset className="mb-4">
<legend className="text-sm font-medium text-gray-700">
{legend}
{required && <span className="text-red-500 ml-1" aria-hidden="true">*</span>}
</legend>
<div className="mt-2 space-y-2" role={type === 'radio' ? 'radiogroup' : undefined} aria-required={required}>
{options.map(option => (
<div key={option.id} className="flex items-center">
<input
type={type}
id={option.id}
name={name}
value={option.value}
checked={type === 'radio' ? values[0] === option.value : values.includes(option.value)}
onChange={(e) => onChange(option.value, e.target.checked)}
aria-describedby={errorId}
className="h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500"
/>
<label htmlFor={option.id} className="ml-2 block text-sm text-gray-700">
{option.label}
</label>
</div>
))}
</div>
{error && (
<p id={errorId} className="mt-1 text-sm text-red-600" role="alert">
{error}
</p>
)}
</fieldset>
);
}Example usage of reusable components:
import { useState } from 'react';
import { TextInput, Textarea, OptionGroup } from '../components/FormElements';
export default function SurveyForm() {
const [formData, setFormData] = useState({
name: '',
email: '',
feedback: '',
satisfaction: '',
interests: [] as string[]
});
const [errors, setErrors] = useState<Record<string, string>>({});
const handleInputChange = (field: string, value: string) => {
setFormData(prev => ({ ...prev, [field]: value }));
// Remove error after editing
if (errors[field]) {
setErrors(prev => {
const newErrors = { ...prev };
delete newErrors[field];
return newErrors;
});
}
};
const handleCheckboxChange = (value: string, checked: boolean) => {
setFormData(prev => {
if (checked) {
return { ...prev, interests: [...prev.interests, value] };
} else {
return { ...prev, interests: prev.interests.filter(item => item !== value) };
}
});
// Remove error after editing
if (errors.interests) {
setErrors(prev => {
const newErrors = { ...prev };
delete newErrors.interests;
return newErrors;
});
}
};
const handleRadioChange = (value: string, checked: boolean) => {
if (checked) {
setFormData(prev => ({ ...prev, satisfaction: value }));
// Remove error after editing
if (errors.satisfaction) {
setErrors(prev => {
const newErrors = { ...prev };
delete newErrors.satisfaction;
return newErrors;
});
}
}
};
const validateForm = () => {
const newErrors: Record<string, string> = {};
if (!formData.name.trim()) {
newErrors.name = 'Name is required';
}
if (!formData.email.trim()) {
newErrors.email = 'Email is required';
} else if (!/^\S+@\S+\.\S+$/.test(formData.email)) {
newErrors.email = 'Please provide a valid email address';
}
if (!formData.feedback.trim()) {
newErrors.feedback = 'Feedback is required';
}
if (!formData.satisfaction) {
newErrors.satisfaction = 'Please select a satisfaction level';
}
if (formData.interests.length === 0) {
newErrors.interests = 'Select at least one category';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (validateForm()) {
// Submit the form
console.log('Form data:', formData);
alert('Form sent successfully!');
}
};
return (
<div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-md">
<h1 className="text-2xl font-bold mb-6">User survey</h1>
<form onSubmit={handleSubmit} noValidate>
<TextInput
id="name"
label="Full name"
required
value={formData.name}
onChange={(e) => handleInputChange('name', e.target.value)}
error={errors.name}
/>
<TextInput
id="email"
label="Email"
type="email"
required
value={formData.email}
onChange={(e) => handleInputChange('email', e.target.value)}
error={errors.email}
hint="We'll never share your email address"
/>
<Textarea
id="feedback"
label="Your feedback"
required
value={formData.feedback}
onChange={(e) => handleInputChange('feedback', e.target.value)}
error={errors.feedback}
rows={4}
/>
<OptionGroup
legend="Satisfaction level"
name="satisfaction"
type="radio"
required
values={formData.satisfaction ? [formData.satisfaction] : []}
onChange={handleRadioChange}
error={errors.satisfaction}
options={[
{ id: 'satisfaction-very-satisfied', value: 'very-satisfied', label: 'Very satisfied' },
{ id: 'satisfaction-satisfied', value: 'satisfied', label: 'Satisfied' },
{ id: 'satisfaction-neutral', value: 'neutral', label: 'Neutral' },
{ id: 'satisfaction-dissatisfied', value: 'dissatisfied', label: 'Dissatisfied' },
{ id: 'satisfaction-very-dissatisfied', value: 'very-dissatisfied', label: 'Very dissatisfied' }
]}
/>
<OptionGroup
legend="Interests"
name="interests"
type="checkbox"
required
values={formData.interests}
onChange={handleCheckboxChange}
error={errors.interests}
options={[
{ id: 'interests-technology', value: 'technology', label: 'Technology' },
{ id: 'interests-design', value: 'design', label: 'Design' },
{ id: 'interests-business', value: 'business', label: 'Business' },
{ id: 'interests-health', value: 'health', label: 'Health' },
{ id: 'interests-education', value: 'education', label: 'Education' }
]}
/>
<div className="mt-6">
<button
type="submit"
className="w-full py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
>
Send survey
</button>
</div>
</form>
</div>
);
}Testing form accessibility
Merely implementing accessible forms is only half the battle. Testing them is also necessary:
1. Automated accessibility testing
You can use tools like @axe-core/react to test accessibility during development:
// In the test file (e.g., FormComponent.test.tsx)
import React from 'react';
import { render } from '@testing-library/react';
import { axe, toHaveNoViolations } from 'jest-axe';
import ContactForm from '../ContactForm';
// Add matcher to Jest
expect.extend(toHaveNoViolations);
describe('ContactForm', () => {
it('should not have accessibility violations', async () => {
const { container } = render(<ContactForm />);
const results = await axe(container);
expect(results).toHaveNoViolations();
});
});2. Manual accessibility testing
Automated tests don't catch all problems. Manual testing is also required:
Keyboard navigation testing:
- Can you navigate the form using only the keyboard (Tab, Shift+Tab, Enter, space)?
- Is focus clearly visible on every field?
- Can you activate buttons and links with the keyboard?
Testing with screen readers:
- NVDA or JAWS (Windows)
- VoiceOver (macOS)
- TalkBack (Android)
- VoiceOver (iOS)
Zoom testing:
- Is the form usable when text is zoomed to 200%?
- Does the form layout adapt to zooming?
3. Form accessibility checklist
Before deploying a form, check it against the following criteria:
Structural:
- Do all form fields have associated labels?
- Are radio and checkbox fields grouped with
<fieldset>and<legend>? - Are ARIA attributes used correctly?
Interactivity:
- Can you navigate the form via keyboard?
- Can you activate all controls with the keyboard?
- Is keyboard focus visible?
Feedback:
- Are validation errors clearly communicated?
- Are error messages linked to fields via
aria-describedby? - Is the form submission status clearly communicated?
Visual:
- Is the text/background contrast sufficient (minimum 4.5:1)?
- Is the form usable at various screen sizes?
- Are visual indicators (e.g., colors) complemented by other cues?
Summary
Creating usable and accessible forms is a key aspect of modern web applications. Properly designed forms contribute to increased conversion, improved user experience, and provide access to your services to a wider audience.
Main principles to remember:
- Clear structure - logical field organization, clear labels, grouping of related fields
- Keyboard accessibility - full keyboard support, visible focus, logical tab order
- Correct ARIA - using ARIA attributes to improve screen reader users' experience
- Effective communication - clear labels, helper texts, precise error messages
- Validation - immediate feedback, clear instructions, validation both on client and server
- Testing - both automated and manual, with various assistive devices
By building forms following these principles, you can create an accessible and user-friendly experience that will serve all visitors to your application.
Code for this lesson: App.tsx
import React, { useState, useRef, useEffect } from 'react';
// Form accessibility - ARIA, labels, focus management
interface A11yIssue {
id: string;
label: string;
bad: string;
good: string;
description: string;
}
const a11yIssues: A11yIssue[] = [
{
id: 'labels',
label: 'Label + htmlFor',
bad: '<input placeholder="Email" />',
good: '<label htmlFor="email">Email</label>\n<input id="email" />',
description: 'Every field must have an associated label. Screen readers read the label.',
},
{
id: 'aria',
label: 'aria-describedby',
bad: '<input />\n<span>Min. 8 characters</span>',
good: '<input aria-describedby="hint" />\n<span id="hint">Min. 8 characters</span>',
description: 'aria-describedby links the field to an error description or hint.',
},
{
id: 'error',
label: 'aria-invalid + role="alert"',
bad: '<input style={{border:"red"}} />\n<span>Error!</span>',
good: '<input aria-invalid="true" />\n<span role="alert">Error!</span>',
description: 'aria-invalid and role="alert" inform screen readers about errors.',
},
{
id: 'focus',
label: 'Focus management',
bad: '// No focus management\n// The user does not know where the error is',
good: '// After an error - focus the first invalid input\nfirstErrorRef.current?.focus()',
description: 'After a validation error, move focus to the first invalid element.',
},
];
export default function AccessibilityDemo() {
const [selected, setSelected] = useState<A11yIssue>(a11yIssues[0]);
const [showDemo, setShowDemo] = useState(false);
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [errors, setErrors] = useState<Record<string, string>>({});
const nameRef = useRef<HTMLInputElement>(null);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const errs: Record<string, string> = {};
if (!name) errs.name = 'Name is required';
if (!email) errs.email = 'Email is required';
else if (!/\S+@\S+\.\S+/.test(email)) errs.email = 'Invalid email';
setErrors(errs);
// Focus management - move to the first invalid input
if (Object.keys(errs).length > 0 && errs.name) {
nameRef.current?.focus();
}
};
const inputStyle: React.CSSProperties = {
width: '100%', padding: '10px', background: '#0d1117',
border: '1px solid #333', borderRadius: 6, color: '#e0e0e0',
fontFamily: 'monospace', fontSize: 13, boxSizing: 'border-box'
};
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
<h1 style={{ color: '#64ffda' }}>Form Accessibility (a11y)</h1>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
{a11yIssues.map(issue => (
<button key={issue.id} onClick={() => setSelected(issue)} style={{
background: selected.id === issue.id ? '#1565c0' : '#1a2744',
color: '#fff', border: `1px solid ${selected.id === issue.id ? '#64ffda' : '#333'}`,
borderRadius: 6, padding: '6px 12px', cursor: 'pointer', fontSize: 11, fontFamily: 'monospace'
}}>
{issue.label}
</button>
))}
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
<div style={{ background: '#3e1010', borderRadius: 8, padding: 12, border: '1px solid #f44336' }}>
<div style={{ color: '#f44336', fontSize: 12, marginBottom: 8 }}>Bad (inaccessible):</div>
<pre style={{ color: '#ffcdd2', fontSize: 11, margin: 0, whiteSpace: 'pre-wrap' }}>{selected.bad}</pre>
</div>
<div style={{ background: '#0d2818', borderRadius: 8, padding: 12, border: '1px solid #4caf50' }}>
<div style={{ color: '#4caf50', fontSize: 12, marginBottom: 8 }}>Good (accessible):</div>
<pre style={{ color: '#c8e6c9', fontSize: 11, margin: 0, whiteSpace: 'pre-wrap' }}>{selected.good}</pre>
</div>
</div>
<p style={{ color: '#aaa', fontSize: 13, marginBottom: 16 }}>{selected.description}</p>
<button onClick={() => setShowDemo(!showDemo)} style={{
background: '#9c27b0', color: '#fff', border: 'none', borderRadius: 6,
padding: '8px 16px', cursor: 'pointer', fontFamily: 'monospace', marginBottom: 16
}}>
{showDemo ? 'Hide' : 'Show'} accessible demo form
</button>
{showDemo && (
<form onSubmit={handleSubmit} style={{ maxWidth: 400 }} aria-label="Registration form">
<div style={{ marginBottom: 12 }}>
<label htmlFor="a11y-name" style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>
Name *
</label>
<input
ref={nameRef} id="a11y-name" value={name}
onChange={e => setName(e.target.value)}
aria-invalid={!!errors.name} aria-describedby={errors.name ? 'name-error' : undefined}
style={{ ...inputStyle, borderColor: errors.name ? '#f44336' : '#333' }}
/>
{errors.name && <div id="name-error" role="alert" style={{ color: '#f44336', fontSize: 11, marginTop: 4 }}>{errors.name}</div>}
</div>
<div style={{ marginBottom: 12 }}>
<label htmlFor="a11y-email" style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>
Email *
</label>
<input
id="a11y-email" type="email" value={email}
onChange={e => setEmail(e.target.value)}
aria-invalid={!!errors.email} aria-describedby="email-hint"
style={{ ...inputStyle, borderColor: errors.email ? '#f44336' : '#333' }}
/>
<div id="email-hint" style={{ color: '#888', fontSize: 11, marginTop: 4 }}>
{errors.email ? <span role="alert" style={{ color: '#f44336' }}>{errors.email}</span> : 'Format: name@domain.com'}
</div>
</div>
<button type="submit" style={{
background: '#4caf50', color: '#fff', border: 'none', borderRadius: 6,
padding: '10px 20px', cursor: 'pointer', fontFamily: 'monospace', width: '100%'
}}>
Submit (with focus management)
</button>
</form>
)}
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the recommended error handling pattern in Server Actions in Next.js?
2. The useActionState hook (formerly useFormState) in Server Actions is used for:
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Create a reusable custom hook useForm with validation, submission handling, and error management
- Code editor
Create a photo upload form with preview, drag&drop, progress bar, and type/size validation
- Code editor
Create a form where fields appear conditionally based on previous selections (e.g., payment method -> different fields)
- Vertical ordering
Arrange the elements in the correct order: Setup provider โ Create login โ Protect routes โ Handle sessions
- Click in order
Click elements in order to build the syntax <form action={serverAction}>
- Click in order
Click elements in order to build the Zod validation chain: z.string().email().min(5)
Tasks after this lesson
- QuestionError Handling Pattern in Server Actions
- QuestionThe useActionState Hook in Server Actions
- Coding taskPractice: Create a reusable custom hook useForm with validation,
- QuestionFile uploads in forms require:
- QuestionDebouncing in forms is used for:
- Coding taskPractice: Create a photo upload form with preview,
- Coding taskPractice: Create a form where fields appear
- Put in orderSequence: Setup provider โ Create login โ Protect routes
- Click in orderForm Syntax with Server Action
- Click in orderZod Validation Chain for Email