PHP Form Validation for Beginners: Simple Step-by-Step
Learn PHP form validation for beginners: check empty fields, validate emails and show clear errors with simple, copy-paste code and line-by-line explanations.
Learn PHP form validation for beginners: check empty fields, validate emails and show clear errors with simple, copy-paste code and line-by-line explanations.
PHP form validation for beginners means checking what a visitor typed into a form before you use it. In plain words: you make sure the name is not empty, the email looks like an email, and the age is a real number. If something is wrong, you show a friendly message instead of saving bad data.
This guide assumes you know nothing about validation. We build one small form step by step. Every term is explained the first time it appears, and every code block is followed by a line-by-line explanation.
A form lets visitors send information to your website. Validation is the step where your PHP code checks that information. Visitors make typing mistakes. Some visitors also send bad data on purpose. You should never trust what comes from a form.
There are two kinds of work here. Validation checks that data is correct. Sanitizing cleans the data, for example by removing extra spaces or dangerous characters. Good forms do both.
We start with a form that asks for a name and an email. The form sends its data to the same page using the POST method. If you are not sure what POST means, read our guide on PHP form handling first (link below).
<form method="post" action="">
<label>Name: <input type="text" name="name"></label>
<label>Email: <input type="text" name="email"></label>
<button type="submit">Send</button>
</form>Line 1 opens the form. method="post" hides the data from the web address, and action="" sends it back to the same page. Lines 2 and 3 are input boxes. The name attribute is important, because PHP uses it to find the value. Line 4 is the submit button.
New to forms? Read our PHP form handling guide first, then come back here.
Read: PHP form handling (GET vs POST)When someone first opens the page, the form is empty. We only want to validate after they press the button. PHP stores request details in a built-in array called $_SERVER. One of its values tells us the request method.
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
echo "The form was submitted.";
}Line 1 starts PHP. Line 2 asks: was this page requested with POST? The triple equals sign checks for an exact match. If yes, the code inside the braces runs. On a normal page visit the method is GET, so nothing happens.
PHP puts submitted values in another built-in array called $_POST. You read a value with its input name. A field may be missing, so we use the null coalescing operator (??). It gives a default value when the key does not exist, which avoids errors.
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");$_POST["name"] gets the typed name. ?? "" means: if it is missing, use an empty string. trim() removes spaces at the start and end, so a name made of only spaces counts as empty.
Now we check the values. We collect problems in an array called $errors. If the array is empty at the end, the form is valid.
$errors = [];
if ($name === "") {
$errors["name"] = "Please enter your name.";
} elseif (strlen($name) > 50) {
$errors["name"] = "Name must be 50 characters or fewer.";
}
if ($email === "") {
$errors["email"] = "Please enter your email.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "That email address does not look right.";
}Line 1 creates an empty list of errors. The name check says: if it is empty, add a message; else if it is longer than 50 characters, add a different message. strlen() counts characters. For the email, filter_var() with FILTER_VALIDATE_EMAIL is PHP's built-in email checker. The ! means "not", so the error is added when the email is not valid.
| Tool | What it does | Example |
|---|---|---|
| trim() | Removes spaces at both ends | trim(" Ann ") |
| strlen() | Counts characters | strlen("Ann") gives 3 |
| filter_var() with FILTER_VALIDATE_EMAIL | Checks email format | filter_var($email, FILTER_VALIDATE_EMAIL) |
| filter_var() with FILTER_VALIDATE_INT | Checks for a whole number | filter_var($age, FILTER_VALIDATE_INT) |
| htmlspecialchars() | Makes text safe to show on a page | htmlspecialchars($name) |
If there are errors, show them. Nobody likes retyping everything, so we also put the typed values back in the boxes. Because we print user text into HTML, we wrap it in htmlspecialchars(). This turns characters like < and > into harmless text and helps prevent a problem called cross-site scripting (XSS).
<form method="post" action="">
<label>Name:
<input type="text" name="name"
value="<?= htmlspecialchars($name ?? "") ?>">
</label>
<span><?= $errors["name"] ?? "" ?></span>
<label>Email:
<input type="text" name="email"
value="<?= htmlspecialchars($email ?? "") ?>">
</label>
<span><?= $errors["email"] ?? "" ?></span>
<button type="submit">Send</button>
</form><?= ... ?> is a short way to print a PHP value inside HTML. The value attribute refills the box with what the visitor typed, made safe by htmlspecialchars(). The span after each box prints that field's error message, or nothing if there is none.
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// ... read and validate as shown above ...
if (empty($errors)) {
echo "Thanks, " . htmlspecialchars($name) . "!";
// Safe to save to a database or send an email here
}
}empty($errors) is true when the list has no problems. Only then do we thank the user and continue. This is where you would save the data. If you save to a database, always use prepared statements; see our guide on inserting form data into a database.
Ready to save validated data? Learn how to insert form data into a database with PHP.
Read: Insert form data with PHPForm validation is checking the data a visitor sent through a form before you use it. You test that required fields are filled, that formats such as email are correct, and that lengths are reasonable. Invalid data gets an error message instead of being saved.
Use filter_var($email, FILTER_VALIDATE_EMAIL). It returns the email if the format is valid and false if not. It only checks the format, not whether the mailbox really exists.
Validation checks whether data is acceptable and rejects it if not. Sanitization changes data to make it safe or clean, such as trimming spaces or escaping HTML. Most forms need both.
No. The required attribute is only a convenience in the browser, and anyone can remove or skip it. You must always validate again on the server in PHP.
It converts special characters like < and > into safe HTML codes. That way, text typed by a visitor is shown as text and not run as code in the browser. Use it whenever you print user input on a page.
Want help building safe, professional forms for your website? Talk to the Fepiq team.
Contact FepiqOccasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.
Keep reading
Learn SQL CASE WHEN step by step. This beginner guide shows how to label, group and sort data with simple examples you can copy and run today.
PostgreSQL ILIKE explained for beginners: search text without worrying about case, learn % and _ wildcards, and copy simple examples you can run today.
Let's build something
Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.