About Lesson
PHP Form Validation
Why Validation is Important?
Forms allow users to give input, but:
- A user might enter the wrong data, for example, typing a name in the email field.
- A user might leave required fields blank.
- A malicious user might try to hack the system, such as through XSS or SQL injection.
That’s why validation means checking the data and making it safe.
Two Steps in Validation:
- Validation: Check if the data is correct, including format, type, and required fields.
- Sanitization: Clean the data by removing spaces, slashes, HTML tags, and other unwanted characters.
Common Types of Validation:
1. Required Field Check – Did the user leave it blank?
PHP
if (empty($_POST["name"])) {
echo "Name is required";
}
2. Email Validation – Is it in the correct format?
PHP
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
}
3. Number Validation – Is it a number?
PHP
if (!is_numeric($age)) {
echo "Age must be a number";
}
4. String Length Check – Does it meet min/max length?
PHP
if (strlen($password) < 6) {
echo "Password must be at least 6 characters";
}
5. Data Sanitization – Clean input to prevent attacks.
PHP
function clean_input($data) {
$data = trim($data); // remove spaces
$data = stripslashes($data); // remove slashes
$data = htmlspecialchars($data); // convert <script> into safe text
return $data;
}
Example: Basic Form + Validation
HTML
<!-- FORM.HTML-->
<form method="post" action="validate.php">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
Age: <input type="text" name="age"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
PHP
//VALIDATE.PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Sanitize function
function clean_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Name Validation
if (empty($_POST["name"])) {
echo "❌ Name is required.<br>";
} else {
$name = clean_input($_POST["name"]);
echo "✅ Name: $name <br>";
}
// Email Validation
if (empty($_POST["email"])) {
echo "❌ Email is required.<br>";
} elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
echo "❌ Invalid email format.<br>";
} else {
$email = clean_input($_POST["email"]);
echo "✅ Email: $email <br>";
}
// Age Validation
if (empty($_POST["age"])) {
echo "❌ Age is required.<br>";
} elseif (!is_numeric($_POST["age"])) {
echo "❌ Age must be a number.<br>";
} elseif ($_POST["age"] < 18) {
echo "❌ You must be at least 18 years old.<br>";
} else {
$age = clean_input($_POST["age"]);
echo "✅ Age: $age <br>";
}
// Password Validation
if (empty($_POST["password"])) {
echo "❌ Password is required.<br>";
} elseif (strlen($_POST["password"]) < 6) {
echo "❌ Password must be at least 6 characters long.<br>";
} else {
$password = clean_input($_POST["password"]);
echo "✅ Password looks good.<br>";
}
}
?>