AJAX Form Validation with PHP and JavaScript
AJAX validation can make forms easier to use by returning field errors without reloading the page. The server remains authoritative: client-side checks can be bypassed.
A simple PHP validation endpoint
header('Content-Type: application/json; charset=utf-8');
$name = trim((string)($_POST['name'] ?? ''));
$errors = [];
if ($name === '' || mb_strlen($name) > 80) {
$errors['name'] = 'Enter a name of up to 80 characters.';
}
if ($errors) {
http_response_code(422);
echo json_encode(['errors' => $errors]);
exit;
}
echo json_encode(['message' => 'Form data is valid.']);
Display errors safely
Use textContent to insert messages as text. Associate each message with its input and set aria-invalid when validation fails. Clear stale errors when the user corrects a field.
Production checklist
Validate type, length, format, and allowed values. Add CSRF protection, rate limiting where abuse is possible, and authorization for protected actions. Never rely on a successful client-side check before writing to the database.