Table of Contents:
PHP Form Validation Tutorial (Complete Guide with Examples)
Welcome to phponline.in, your complete guide to mastering PHP programming.
In this tutorial, you will learn PHP Form Validation in detail:
- Why validation is important
- Client-side vs server-side validation
- Required field validation in PHP
- Email, phone number, and password validation
- Input sanitization methods
- Validation using
filter_var()
and Regular Expressions (Regex) - Real-world projects: login form, registration form, contact form validation
- Security best practices in form validation
👉 Related: PHP Form Handling
You Will Learn
- Introduction to PHP Form Validation
- Importance of Form Validation
- Client-Side vs Server-Side Validation
- PHP Superglobals for Validation
- Basic Required Field Validation
- Email Validation in PHP
- Password Validation in PHP
- Username Validation (Letters and Numbers Only)
- Phone Number Validation in PHP
- Age and Number Validation
- URL Validation
- Date Validation
- File Upload Validation
- Radio Button Validation
- Checkbox Validation
- Dropdown (Select) Validation
- Textarea Validation
- Password Strength Check (Regex Example)
- Matching Passwords Validation (Confirm Password)
- Multiple Field Validation Example
- Sticky Forms (Retaining Input After Errors)
- Using
filter_var()
for Validation - Validation with Regex in PHP
- Sanitizing Input with
htmlspecialchars()
- Sanitizing with
trim()
,stripslashes()
,strip_tags()
- Preventing XSS with Form Validation
- Preventing SQL Injection with Validation + Prepared Statements
- PHP Error Messages for Invalid Inputs
- Displaying Validation Errors Near Form Fields
- PHP Validation Functions (Reusable Code)
- Contact Form Validation Example
- Registration Form Validation Example
- Login Form Validation Example
- Feedback Form Validation Example
- Secure Form Validation Workflow
- Validation and Database Insertion (MySQL Example)
- Real-World Example: Newsletter Signup Form Validation
- Real-World Example: Survey Form Validation
- Secure File Upload Form Validation
- Multi-Step Form Validation
- Using Sessions in Form Validation
- Using Cookies with Validation (Optional)
- PHP Form Validation Best Practices
- Common Mistakes in Validation
- Validation Checklist for Secure Forms
- Mini Project 1: Validated Registration Form with MySQL
- Mini Project 2: Validated Contact Form with Email Sending
- Mini Project 3: Validated Login System with Sessions
- PHP Form Validation Security Tips
1. Introduction to PHP Form Validation
Form validation in PHP ensures that the data entered by users is correct, complete, and safe before storing or using it.
Without validation, users might:
- Leave fields blank
- Enter invalid data (e.g., text instead of numbers)
- Insert malicious code (XSS or SQL Injection)
👉 Example: A user enters “abc” in an age field. Validation ensures only a number is accepted.
5. Basic Required Field Validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
echo "Name is required";
} else {
$name = htmlspecialchars($_POST["name"]);
echo "Welcome, $name";
}
}
👉 Related: PHP Variables
6. Email Validation in PHP
$email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
echo "Valid email";
}
7. Password Validation in PHP (Minimum Length)
$password = $_POST["password"];
if (strlen($password) < 6) {
echo "Password must be at least 6 characters long";
}
👉 Related: PHP Strings
10. Age and Number Validation
$age = $_POST["age"];
if (!filter_var($age, FILTER_VALIDATE_INT)) {
echo "Invalid age. Please enter a number.";
}
18. Password Strength Check (Regex Example)
$password = $_POST["password"];
if (!preg_match("/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$/", $password)) {
echo "Password must contain at least 8 characters, one uppercase, one lowercase, and one digit.";
}
23. Validation with Regex in PHP
- Email Regex:
/^[\w.-]+@[\w.-]+\.[a-z]{2,}$/i
- Phone Regex:
/^[0-9]{10}$/
- Username Regex:
/^[A-Za-z0-9_]{3,20}$/
31. Contact Form Validation Example
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$message = trim($_POST["message"]);
if (empty($name) || empty($email) || empty($message)) {
echo "All fields are required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
echo "Thank you, $name. We received your message.";
}
}
👉 Related: PHP Form Handling
32. Registration Form Validation Example
- Validate Name (letters only)
- Validate Email
- Validate Password (min length, confirm password)
- Store securely in MySQL database with prepared statements
36. Validation + Database Insertion
$conn = mysqli_connect("localhost", "root", "", "testdb");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = mysqli_real_escape_string($conn, $_POST["name"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email";
} else {
$sql = "INSERT INTO users (name, email) VALUES (?, ?)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "ss", $name, $email);
mysqli_stmt_execute($stmt);
echo "Registration successful";
}
}
👉 Related: [PHP MySQL Integration]
43. PHP Form Validation Best Practices
- Always validate on the server-side (not only JavaScript).
- Use
filter_var()
for built-in validation. - Sanitize input before displaying.
- Use prepared statements for DB queries.
- Display clear error messages near fields.
Mini Project: Validated Registration Form with MySQL
Includes:
- Name, Email, Password, Confirm Password fields
- Validation for required fields, email format, password strength
- Data stored in MySQL database securely
Summary & Conclusion
- PHP Form Validation ensures security and correctness of data.
- Always validate + sanitize user input.
- Use built-in methods like
filter_var()
when possible. - Prevent XSS and SQL Injection with proper validation.
👉 Next, check: PHP Regular Expressions
FAQs on PHP Form Validation
Q1: Why is form validation important in PHP?
A: To ensure users enter valid, secure, and complete data.
Q2: What’s the difference between client-side and server-side validation?
A: Client-side uses JavaScript (quick but insecure), server-side uses PHP (secure).
Q3: How to validate email in PHP?
A: Use filter_var($email, FILTER_VALIDATE_EMAIL)
.
Q4: How to validate passwords in PHP?
A: Check length, complexity, and use regex for strong password rules.
Q5: How to prevent SQL Injection in forms?
A: Always use prepared statements with parameter binding.