Form and Spelling Validation in PHP
PHP form validation checks whether submitted values meet your rules before you save them. An email needs a valid format, a display name needs a sensible length, and a password must meet your account requirements.
HTML can catch simple mistakes before submission, but PHP must check the values again. Database constraints prevent invalid records, and output escaping keeps submitted text from becoming HTML. Spellchecking is optional help for the writer, not a security check.
This sits in the intermediate PHP tutorial track because the code crosses HTML, server-side branching, sessions, SQL constraints, and output escaping. If the server-side rules themselves are still fuzzy, read PHP conditionals and control flow and PHP email validation first. Most validation bugs are ordinary branches with the wrong comparison or a missing failure path.
What Should PHP Form Validation Check?
PHP form validation checks required fields, data types, formats, and lengths. Other protections have separate jobs:
- Browser hints help the user correct obvious mistakes.
- Server validation decides whether the request is acceptable.
- CSRF protection checks a submitted token against the session token to help prevent cross-site request forgery.
- SQL constraints enforce facts that must remain true after the PHP request is gone.
- Output escaping makes accepted text safe in the output context where it appears.
Those jobs are related, but they are not interchangeable. required on an HTML field does not protect the server. A database UNIQUE constraint does not give the user a friendly form error by itself. htmlspecialchars() does not prove the email address is syntactically valid. A CSRF token does not make the submitted title a good title.
Can HTML Replace PHP Form Validation?
HTML constraints cannot replace PHP validation because anyone can send a request without using your form. Attributes such as required and minlength still give people useful feedback before submission:
<form method="post" action="/register">
<label>
Email
<input name="email" type="email" required autocomplete="email">
</label>
<label>
Display name
<input name="display_name" required minlength="2" maxlength="60">
</label>
<label>
Password
<input name="password" type="password" required minlength="12" autocomplete="new-password">
</label>
<button type="submit">Create account</button>
</form> MDN is explicit that client-side validation is a usability feature. The server still has to repeat the rules because the browser is not the authority. Anyone can send a POST request without your form.
Use the HTML layer for fast feedback. Use PHP for the decision that matters.
How Do You Validate Form Fields in PHP?
PHP validates form fields by checking their types first, then applying the rules for each field. This example requires the mbstring extension and returns errors alongside the accepted values.
<?php
/**
* @return array{0: array<string, string>, 1: array<string, string>}
*/
function validateRegistration(array $input): array
{
$email = is_string($input["email"] ?? null) ? trim($input["email"]) : "";
$displayName = is_string($input["display_name"] ?? null) ? trim($input["display_name"]) : "";
$password = is_string($input["password"] ?? null) ? $input["password"] : "";
$errors = [];
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors["email"] = "Enter a valid email address.";
}
$displayNameLength = mb_strlen($displayName, "UTF-8");
if ($displayNameLength < 2 || $displayNameLength > 60) {
$errors["display_name"] = "Use 2 to 60 characters.";
}
if (mb_strlen($password, "UTF-8") < 12 || strlen($password) > 72) {
$errors["password"] = "Use at least 12 characters and no more than 72 bytes.";
}
return [
$errors,
[
"email" => $email,
"display_name" => $displayName,
"password" => $password,
],
];
} PHP's FILTER_VALIDATE_EMAIL is a syntax check, not a deliverability guarantee. It tells you whether the string looks like an email address. It does not prove the mailbox exists, that the user owns it, or that mail will arrive. Confirmation emails and bounce handling are different layers.
mb_strlen() counts Unicode characters rather than bytes. This example also rejects passwords above 72 bytes because it uses bcrypt below, which otherwise truncates longer input. Store the hash, never the password itself.
How Should PHP Display Form Errors?
A PHP form handler should redisplay invalid fields with specific error messages and save data only when validation passes. The abbreviated handler below assumes your application provides the database connection, CSRF helper, and form view; the form also needs a hidden CSRF token.
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] === "POST") {
verifyCsrfToken($_POST["csrf_token"] ?? "");
[$errors, $data] = validateRegistration($_POST);
if ($errors !== []) {
require __DIR__ . "/../views/register.php";
return;
}
createUser(db(), $data["email"], $data["display_name"], $data["password"]);
header("Location: /welcome", true, 303);
return;
}
require __DIR__ . "/../views/register.php"; The 303 redirect after a successful POST prevents a refresh from resubmitting the form and keeps the browser history honest.
CSRF protection belongs in this flow because form validation and request legitimacy are different questions. Read PHP security fundamentals before accepting real account data, especially if the form changes state.
Why Does a Validated Form Need Database Constraints?
Database constraints reject invalid records even when two requests arrive together or another script writes to the table. This PostgreSQL schema requires a unique email address and a display name between 2 and 60 characters.
CREATE TABLE users (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL CHECK (char_length(display_name) BETWEEN 2 AND 60),
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
); The unique email rule belongs in the database because two PHP requests can race each other. One request validates, another request inserts, and then the first request tries to insert the same email. The database is the layer that can settle that race reliably.
This is where form validation crosses into schema design. If a rule must remain true no matter which PHP file, queue worker, import script, or admin tool writes the row, the schema should carry it.
Escape Output at Render Time
Accepted input is still input, so escape it when rendering HTML:
<input
name="display_name"
value="<?= htmlspecialchars($data["display_name"] ?? "", ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") ?>"> That is output escaping rather than validation, because the user may be allowed to have an apostrophe or angle bracket in a field depending on the application. The question is how that value is represented safely in HTML.
If a field intentionally accepts HTML, do not treat htmlspecialchars() as a full content policy. Use a real sanitizer with a strict allowlist, and be honest about the risk.
Should PHP Forms Check Spelling?
PHP forms can offer spelling suggestions for comments and other prose, but spelling mistakes should not normally block submission. Browser spellchecking is enough for many forms. Server-side Pspell remains available separately through PECL after its removal from the PHP bundle in 8.4.
For ordinary text fields, use the browser's spelling support:
<textarea
name="body"
rows="8"
spellcheck="true"
maxlength="5000"></textarea> The browser may underline likely spelling mistakes without blocking submission. Support varies, and enhanced spellchecking may send text to a third-party service. Disable spellchecking for sensitive text.
If your product needs server-side spellchecking, treat it as an editorial workflow. Run it after the text is saved as a draft, show suggestions as suggestions, and let a human decide. Do not reject a name, product code, domain, username, or medical term because a dictionary disagrees with it.
Older validation scripts loved regular expressions and word lists because they gave the appearance of certainty. Real user data is messier, so enforce only the rules the application needs.
Save Validated Values with Prepared Statements
Once validation passes, the insert still uses prepared statements:
<?php
function createUser(PDO $pdo, string $email, string $displayName, string $password): void
{
$statement = $pdo->prepare(
"INSERT INTO users (email, display_name, password_hash)
VALUES (:email, :display_name, :password_hash)",
);
$statement->execute([
"email" => $email,
"display_name" => $displayName,
"password_hash" => password_hash($password, PASSWORD_BCRYPT),
]);
} Prepared statements keep submitted values separate from SQL instructions. Validation checks whether those values are acceptable; neither replaces the other.
For a fuller database-backed shape, read PHP and MySQL with PDO and building a small PHP database app. If the same input arrives as JSON instead of a browser form, the validation principle is unchanged; the PHP API guide covers that boundary. When the accepted form data triggers a notification, continue to sending email in PHP.
Check Input Before Saving It
Check form values in PHP even when HTML has already checked them.
Return clear errors, save accepted values through prepared statements, and escape text when displaying it. Keep spelling suggestions optional.
Frequently Asked Questions
How should you validate an email address in PHP?
PHP checks email syntax with filter_var() and FILTER_VALIDATE_EMAIL. A valid format does not prove that the address receives mail. Send a confirmation link to check that the person can access the mailbox.
Should PHP trim form input before validation?
PHP should trim form input when leading or trailing spaces have no meaning, such as in an email address. Trim before checking length. Do not trim passwords because spaces may be part of the password.
How does PHP validate a date submitted by a form?
PHP validates a submitted date by parsing the expected format and checking that the result matches the original value. That rejects dates such as February 31, which a parser may otherwise move into the next month.
Should PHP form errors name the field that failed?
PHP form errors should name the affected field and explain how to fix it. Keep non-sensitive values in the form and place each message beside its field. Never refill a password field.
Does every text field in a PHP form need spellchecking?
Not every text field in a PHP form needs spellchecking. Enable it for prose such as comments, and disable it for usernames, codes, and reference numbers. Browser defaults and support vary.
Sources
-
[1]
PHP filter validation examples(php.net)
-
[2]
PHP htmlspecialchars(php.net)
-
[3]
PHP mb_strlen(php.net)
-
[4]
PHP Pspell(php.net)
-
[5]
Client-side form validation(developer.mozilla.org)
-
[6]
spellcheck HTML global attribute(developer.mozilla.org)
-
[7]
Input Validation Cheat Sheet(cheatsheetseries.owasp.org)
-
[8]
Cross-Site Request Forgery Prevention Cheat Sheet(cheatsheetseries.owasp.org)
-
[9]
PostgreSQL Constraints(postgresql.org)
Read Next
Validate email-address shape in PHP with filter_var, then separate syntax checks from confirmation, deliverability, and account ownership.
Secure ordinary PHP surfaces with current password hashing, sessions, CSRF tokens, output escaping, prepared statements, and upload controls.
Design relational tables through a worked normalization example, then add stable keys, constraints, indexes, and safe migrations.