Introduction
Form validation in PHP is an important part of PHP development. It helps ensure that users submit correct and complete information before processing a form. In this chapter, you will learn how to validate names, email addresses, phone numbers, passwords, numbers, and other form data using practical PHP examples.
Question 1: Check Whether a Form Field Is Empty
Problem Statement
Create a PHP program that checks whether a student’s name has been entered. Display an error message if the name is empty.
PHP Solution
<?php
$name = "Rahul";
if (trim($name) === "") {
echo "Student name is required.";
} else {
echo "Student Name: " . htmlspecialchars($name);
}
?>
Sample Output
Student Name: Rahul
Try changing $name to an empty string.
$name = "";
Output:
Student name is required.
Explanation
trim()removes spaces from the beginning and end of a string.- The condition checks whether the name is empty after removing spaces.
htmlspecialchars()safely displays the submitted name.
Concepts Covered
- Empty field validation
trim()- Conditional statements
- Safe output
Question 2: Validate an Email Address
Problem Statement
Create a PHP program that checks whether an email address has a valid format.
PHP Solution
<?php
$email = "rahul@gmail.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid Email Address";
} else {
echo "Invalid Email Address";
}
?>
Sample Output
Valid Email Address
Try changing the email:
$email = "rahulgmail.com";
Output:
Invalid Email Address
Explanation
filter_var()checks whether a value matches a specified filter.FILTER_VALIDATE_EMAILchecks the email address format.- PHP displays a different message depending on the validation result.
Concepts Covered
- Email validation
filter_var()FILTER_VALIDATE_EMAIL- If-Else statements
Question 3: Validate a 10-Digit Mobile Number
Problem Statement
Create a PHP program that checks whether a mobile number contains exactly 10 digits.
PHP Solution
<?php
$mobile = "9876543210";
if (preg_match("/^[0-9]{10}$/", $mobile)) {
echo "Valid Mobile Number";
} else {
echo "Invalid Mobile Number";
}
?>
Sample Output
Valid Mobile Number
Try changing the mobile number:
$mobile = "98765432";
Output:
Invalid Mobile Number
Explanation
The preg_match() function checks whether a string matches a regular expression.
^represents the beginning of the string.[0-9]allows digits from 0 to 9.{10}requires exactly 10 digits.$represents the end of the string.
Concepts Covered
- Mobile number validation
preg_match()- Regular expressions
- Digit checking
Question 4: Validate Age Within a Given Range
Problem Statement
Create a PHP program that checks whether a person’s age is between 18 and 60.
PHP Solution
<?php
$age = 25;
if (!is_numeric($age)) {
echo "Please enter a valid age.";
} elseif ($age >= 18 && $age <= 60) {
echo "Age is valid.";
} else {
echo "Age must be between 18 and 60.";
}
?>
Sample Output
Age is valid.
Try changing the age to 15.
Output:
Age must be between 18 and 60.
Explanation
is_numeric()checks whether the value is numeric.&&requires both conditions to be true.- The age must be at least 18 and no more than 60.
Concepts Covered
- Numeric validation
- Range validation
is_numeric()- Logical AND operator
Question 5: Validate a Password Length
Problem Statement
Create a PHP program that checks whether a password contains at least 8 characters.
PHP Solution
<?php
$password = "Rahul@123";
if (strlen($password) >= 8) {
echo "Password length is valid.";
} else {
echo "Password must contain at least 8 characters.";
}
?>
Sample Output
Password length is valid.
Try changing the password:
$password = "abc123";
Output:
Password must contain at least 8 characters.
Explanation
strlen()returns the length of a string in bytes.- The condition checks whether the password has at least 8 characters for ordinary English letters and numbers.
- Short passwords are rejected.
Concepts Covered
- Password validation
strlen()- Minimum length checking
- Conditional statements
Question 6: Validate a Password Using Multiple Conditions
Problem Statement
Create a PHP program that checks whether a password contains:
- At least 8 characters.
- At least one uppercase letter.
- At least one lowercase letter.
- At least one digit.
PHP Solution
<?php
$password = "Rahul123";
if (
strlen($password) >= 8 &&
preg_match("/[A-Z]/", $password) &&
preg_match("/[a-z]/", $password) &&
preg_match("/[0-9]/", $password)
) {
echo "Password is valid.";
} else {
echo "Password does not meet the requirements.";
}
?>
Sample Output
Password is valid.
Explanation
strlen()checks the minimum length.[A-Z]checks for an uppercase letter.[a-z]checks for a lowercase letter.[0-9]checks for a digit.&&ensures that all conditions must be satisfied.
Concepts Covered
- Multiple password conditions
- Regular expressions
preg_match()- Password validation
Question 7: Validate a Salary Value
Problem Statement
Create a PHP program that checks whether an employee’s salary is numeric and greater than zero.
PHP Solution
<?php
$salary = "35000";
if (!is_numeric($salary)) {
echo "Salary must be numeric.";
} elseif ($salary <= 0) {
echo "Salary must be greater than zero.";
} else {
echo "Valid Salary: ₹" . number_format((float)$salary, 2);
}
?>
Sample Output
Valid Salary: ₹35,000.00
Try changing the salary to:
$salary = "-5000";
Output:
Salary must be greater than zero.
Explanation
is_numeric()checks whether the salary contains a valid numeric value.- The second condition rejects zero and negative values.
number_format()displays the salary with two decimal places.
Concepts Covered
- Salary validation
- Numeric checking
- Negative value checking
- Number formatting
Question 8: Validate a Dropdown Selection
Problem Statement
Create a PHP program that checks whether a student has selected an allowed course.
PHP Solution
<?php
$course = "PHP";
$allowedCourses = [
"PHP",
"Python",
"Java",
"JavaScript"
];
if (in_array($course, $allowedCourses, true)) {
echo "Selected Course: " . htmlspecialchars($course);
} else {
echo "Please select a valid course.";
}
?>
Sample Output
Selected Course: PHP
Try changing the course:
$course = "C#";
Output:
Please select a valid course.
Explanation
$allowedCoursescontains the permitted course names.in_array()checks whether the selected course exists in the array.- The third argument
trueenables strict comparison.
Concepts Covered
- Dropdown value validation
in_array()- Allowed values
- Strict comparison
Question 9: Validate a Website URL
Problem Statement
Create a PHP program that checks whether a website address has a valid URL format.
PHP Solution
<?php
$website = "https://www.example.com";
if (filter_var($website, FILTER_VALIDATE_URL)) {
echo "Valid Website URL";
} else {
echo "Invalid Website URL";
}
?>
Sample Output
Valid Website URL
Try changing the URL:
$website = "www.example";
Output:
Invalid Website URL
Explanation
filter_var()checks the supplied value.FILTER_VALIDATE_URLvalidates the URL format.- A valid URL generally needs a scheme such as
https://.
Concepts Covered
- URL validation
FILTER_VALIDATE_URLfilter_var()- Input checking
Question 10: Build an Employee Registration Validation System
Problem Statement
Create a PHP program that validates employee registration details, including name, email, mobile number, age, and salary. Display a success message only when all details are valid.
PHP Solution
<?php
$name = "Amit Sharma";
$email = "amit@gmail.com";
$mobile = "9876543210";
$age = "28";
$salary = "45000";
$errors = [];
if (trim($name) === "") {
$errors[] = "Employee name is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email address.";
}
if (!preg_match("/^[0-9]{10}$/", $mobile)) {
$errors[] = "Mobile number must contain 10 digits.";
}
if (!filter_var($age, FILTER_VALIDATE_INT) || $age < 18 || $age > 60) {
$errors[] = "Age must be between 18 and 60.";
}
if (!is_numeric($salary) || $salary <= 0) {
$errors[] = "Enter a valid salary.";
}
if (empty($errors)) {
echo "Employee Registration Successful!<br><br>";
echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Email: " . htmlspecialchars($email) . "<br>";
echo "Mobile: " . htmlspecialchars($mobile) . "<br>";
echo "Age: " . htmlspecialchars($age) . "<br>";
echo "Salary: ₹" . number_format((float)$salary, 2);
} else {
echo "Please correct the following errors:<br>";
foreach ($errors as $error) {
echo htmlspecialchars($error) . "<br>";
}
}
?>
Sample Output
Employee Registration Successful!
Name: Amit Sharma
Email: amit@gmail.com
Mobile: 9876543210
Age: 28
Salary: ₹45,000.00
Explanation
- The program stores all validation errors in an array.
- Each employee detail is checked separately.
filter_var()validates email and integer age.preg_match()validates the mobile number.empty()checks whether the errors array is empty.- The employee details are displayed only when every validation passes.
Concepts Covered
- Multiple field validation
- Error handling with arrays
- Email and mobile validation
- Age and salary validation
foreach()loop- Complete validation system
Key Takeaways
- Form validation checks whether submitted information is correct.
trim()helps identify empty text fields.filter_var()validates email addresses and other data.preg_match()checks patterns such as mobile numbers and passwords.strlen()checks string length.is_numeric()checks numeric values.in_array()validates allowed selections.- Always validate data on the PHP server, even if browser-side validation is used.
- Use
htmlspecialchars()when displaying user-provided text. - Never store plain-text passwords; use secure password hashing.
Frequently Asked Questions (FAQs)
1. What is form validation in PHP?
Form validation is the process of checking submitted data to ensure it is complete and follows the required format before processing it.
2. Why is form validation important?
It helps prevent incorrect, incomplete, or unexpected data from entering an application.
3. How do you check an empty field in PHP?
You can use trim() and compare the result with an empty string.
if (trim($name) === "") {
echo "Name is required.";
}
4. How do you validate an email in PHP?
Use filter_var() with FILTER_VALIDATE_EMAIL.
5. How do you validate a mobile number in PHP?
You can use preg_match() with a regular expression that checks the required number of digits.
6. What is the difference between client-side and server-side validation?
Client-side validation runs in the browser, while server-side validation runs on the server. PHP is commonly used for server-side validation.
7. Can HTML validation replace PHP validation?
No. HTML validation improves the user experience, but users can bypass it. Always validate important data on the server.
8. What is filter_var() in PHP?
filter_var() is a PHP function used to filter or validate values, such as checking email addresses and integers.
9. What is preg_match() used for?
preg_match() checks whether a string matches a specified regular expression. It is useful for validating phone numbers, passwords, and other patterns.
10. How can we display multiple validation errors in PHP?
Store error messages in an array and use a foreach() loop to display them.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
