Build Robust Web Forms with Server-Side Validation
Overview
Combine browser-level hints with authoritative server-side validation, safe output encoding, and clear field-level feedback.
Treat browser validation as assistance
HTML attributes such as required, type="email", minlength, and pattern help users catch mistakes early. They are not a security boundary because requests can be sent without the browser interface. Validate every submitted value on the server against the business rules and expected type.
Normalize carefully and validate strictly
Trim values where whitespace is not meaningful, enforce length limits, and validate identifiers against explicit formats. Do not silently transform values in ways that change their meaning. Use parameterized SQL for database operations and encode values when rendering them into HTML.
$email = trim((string)($_POST['email'] ?? ''));
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Enter a valid email address.';
}
Return useful errors
Associate each message with its field using aria-describedby, mark invalid fields with aria-invalid="true", and provide a summary when several fields fail. Preserve safe user input after validation errors. Never echo submitted HTML directly into a page.
Protect state-changing submissions
Use CSRF tokens for authenticated state changes, apply rate limits where abuse is plausible, and use Post/Redirect/Get after successful submissions. Log validation failures at an appropriate level without recording passwords, tokens, or unnecessary personal data. Test empty, malformed, oversized, repeated, and unexpected values.
Implementation checklist
- Define the expected behavior and supported environments.
- Keep security, accessibility, and failure states in the design.
- Measure the result with representative user journeys.
- Document operational assumptions and review them after changes.