Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 147 ยท PHP and the Web

Form Validation

Validate form input in PHP - required fields, lengths, emails, numbers and dates, collecting errors per field, showing messages, and why server-side checks are a must.

Validation is checking that submitted data makes sense before you use it: the name isn't empty, the email looks like an email, the quantity is a whole number between 1 and 99, the date exists, and the end date comes after the start date. When something is wrong, a good form tells the user exactly which field has a problem and what to do about it, and keeps everything else they typed.

The previous lesson, Handling Forms, showed how to read fields safely and convert them with filter_var(). This lesson builds the rest of the workflow: a set of reusable checks, an error list keyed by field name, a small rule-based validator, form re-display with messages next to each field, and the relationship between browser-side and server-side validation.

The runnable examples call the validation code with simulated submissions (plain arrays standing in for $_POST). That's also how you'd test validation code in a real project: it's just functions that take an array and return results.

Server-side validation is not optional

HTML can validate too: required, type="email", min, max, maxlength and pattern make the browser block bad input before it's sent. That's great for the user, who gets instant feedback without a round trip. But it's not a security measure. Anyone can send a request without your form: with browser developer tools, a curl command, or a script.

Terminal
# Skips every HTML attribute: the server receives whatever this says.
curl -X POST https://example.com/register \
  -d "email=not-an-email" -d "age=-5" -d "role=admin"

So the rule is simple: client-side validation is for convenience, server-side validation is for correctness. Always validate in PHP, and add HTML attributes (or JavaScript) on top as a usability bonus. Keep the two in sync, so the browser doesn't accept something the server then rejects, or the reverse.

Validating common kinds of data

Each type of field has its own pitfalls. Here are reliable checks for the most common ones, each returning an error message or null:

PHP Reusable field checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Some notes on these checks:

  • Required should trim first. A field containing only spaces is empty for every practical purpose.
  • Length must count characters with mb_strlen(). strlen('Zoรซ') is 4, because รซ takes two bytes in UTF-8, so a byte count would accept a three-letter name as four characters. (The same byte counting is why the 'Zoรซ' rows in the output are one column off: printf() pads by bytes, too.) See Unicode and Multibyte Strings.
  • Email validation with FILTER_VALIDATE_EMAIL checks the format, not whether the mailbox exists. ana@example fails because it has no dot in the domain. The only real proof is sending a confirmation email with a link.
  • Numbers should be validated as numbers, with ranges. Don't use is_numeric() for form input: it also accepts values like "1e5", ".5" and " 5 ", so "1e5" guests would pass as 100,000, and it says nothing about ranges.
  • Choices are checked against a whitelist with strict comparison.

Be generous in what you accept for names. People have one-word names, very long names, apostrophes (O'Brien), hyphens, spaces and characters from every script. Rules like "letters only" or "at least two words" reject real people. Check length and emptiness, and escape on output.

Validating dates

Dates are a classic source of bugs. An <input type="date"> sends YYYY-MM-DD, but users with older browsers or other tools may send anything. Two checks are needed: the format must be right, and the date must exist. DateTimeImmutable::createFromFormat() checks the format, but it quietly rolls impossible dates over: 2026-02-30 becomes March 2. Formatting the result back and comparing it with the input catches that:

PHP Strict date validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

DateTimeImmutable objects compare with <, > and == directly, and diff() returns a DateInterval whose y property gives whole years, which is the right way to compute an age (subtracting years ignores whether the birthday has passed). %r%a formats the total number of days with a minus sign when the interval is negative. The Dates and Times lesson covers these classes in depth. In real code, pass "today" in as a parameter as the example does, so tests can use a fixed date.

Collecting errors per field

A form with five problems should show all five at once, not one per submission. Collect errors in an array keyed by field name, so the template can show each message next to its field. Validation returns two things: the cleaned data (trimmed, converted to the right types) and the errors:

PHP Validating a whole form

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The valid submission came back cleaned: the name trimmed, the email lowercased and trimmed, and the age converted to int(36). From here on, the rest of the application uses $result['data'], never the raw input. Notice too that the password is not trimmed (spaces can be part of a password) and that its confirmation is compared with strict !==.

Validation and normalization go together: trimming, lowercasing emails, and removing spaces from phone or card numbers before checking them make the rules simpler and the stored data consistent.

A small rule-based validator

Writing if blocks for every field gets repetitive. Frameworks let you describe rules as data instead (Laravel's 'email' => 'required|email|max:255' is a famous example). A tiny version of that idea fits in one function, and building it shows how those libraries work:

PHP A rule-based validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The rules read like a specification of the form, match (see switch and match) maps each rule name to its check, and an unknown rule name throws instead of being silently ignored. Two design decisions are common to real validators too: empty optional fields skip their other rules (so notes may be blank), and each field reports only its first error.

In a real project, you'd use your framework's validator (Laravel, Symfony Validator) or a library rather than maintaining your own. Knowing how they work helps you write custom rules and debug surprising results.

Showing errors in the form

When validation fails, render the form again with three things: an error summary at the top (good for screen-reader users and long forms), a message next to each field, and the user's values still filled in (a sticky form). Mark invalid fields with aria-invalid="true" and link the message with aria-describedby, so assistive technology reads the error together with the field:

PHP Re-displaying a form with error messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The novalidate attribute on the form is there only for this demo, so the browser doesn't block the submission before PHP can show its own messages. Normally you keep the browser's validation on. The summary links jump to the matching field (href="#email"), and the sticky value Bo <Admin> is escaped like every other value.

Writing helpful messages

Error messages are part of your interface. Good ones:

  • Say what's wrong and how to fix it: "Use at least 12 characters for your password", not "Invalid password".
  • Use the field's visible label, not the internal name (event_date).
  • Never blame the user ("You entered an illegal value!"), and never reveal internals ("SQLSTATE[23000]...").
  • For security-sensitive forms like login, stay vague on purpose: "Email or password is incorrect" doesn't reveal which accounts exist.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your HTML form uses required and type="email". Do you still need to validate the email in PHP?

    Browser validation is a convenience. Requests can be crafted with curl, scripts or developer tools, so the server must validate everything itself.
  2. 2. What does strlen('Zoรซ') return, and why does it matter for a length rule?

    strlen() counts bytes. mb_strlen() counts characters, which is what a user means by "at least 4 characters".
  3. 3. DateTimeImmutable::createFromFormat('!Y-m-d', '2026-02-30') returns a date. Which check reliably rejects it?

    The parser rolls February 30 over to March 2 instead of failing. The round trip produces 2026-03-02, which differs from the input, so the date is rejected.
  4. 4. Why should validation errors be stored in an array keyed by field name?

    Keyed errors let the template print each message beside the right input and show a summary, so the user fixes everything in one go.
  5. 5. Which of these should NOT be trimmed before validation?

    Spaces can be a legitimate part of a password. Trimming it would make the stored hash differ from what the user typed at login.

Summary

  • Always validate on the server; HTML attributes and JavaScript are only a usability layer that anyone can bypass.
  • Trim and normalize input first, then check: required, length with mb_strlen(), FILTER_VALIDATE_EMAIL, integer ranges with FILTER_VALIDATE_INT, choices against a whitelist.
  • Validate dates by parsing with createFromFormat('!Y-m-d', ...) and comparing the formatted result with the input to catch rolled-over dates.
  • Collect errors in an array keyed by field, return cleaned and converted data, and use only the cleaned data afterwards.
  • A rule-based validator turns rules like 'required|email|max:100' into checks; frameworks provide full-featured ones.
  • Re-display the form with a summary, per-field messages (aria-invalid, aria-describedby) and escaped sticky values; write messages that say how to fix the problem.

Next: File Uploads