PHP Validation
Form validation in PHP is the process of verifying and checking the data received from an HTML form to ensure that it is accurate, complete, and in the correct format before processing it on the server.
For example, if a user submits an email address, PHP validation checks whether the input is a valid email format. Similarly, an HTML form can contain various input fields such as:
- Text boxes
- Email fields
- Radio buttons
- Checklist
- Checkbox
- Select dropdown
- submit button
These input fields should be validated, which ensures that users have entered appropriate data, especially in required fields.
There is no guarantee that all data received through an HTML form will be valid and correct. Users may make mistakes, miss required values accidentally, or a number of other things could go wrong. For example, a user can attempt to inject malicious code.
That’s why validation is important to validate data. It plays a crucial role in maintaining data integrity and securing your PHP application against malicious attacks.
Note that validation does not modify or remove information from input data. It only confirms that input data meets your expectations. For example, if you expect an email address, validation make sure that the input data is an email address, not a phone number or random text.
What Can You Validate in PHP?
PHP allows you to validate various types of data submitted from a form:
- Empty string
- Validate string
- Validate numbers
- Validate emails
- Validate URL
- Validate Date
PHP validates the form data submitted by an HTML form on the server side, even if client-side JavaScript validation is also used. This is because JavaScript can be disabled on the client side.
Validation of Empty String in PHP
An empty string means the user did not enter any value in the input field. This can happen either by leaving the field blank or by deleting all the characters. In PHP, we can check for this using the built-in empty() function.
Let’s take a simple example in which we will create an HTML form with a name input field and validate whether the field is empty or not by using PHP script.
Example 1: Validate Empty String in PHP
Step 1: Create an HTML form and save it as form.html.
<!DOCTYPE html>
<html>
<head>
<title>Validate Empty String Example</title>
</head>
<body>
<form method="post" action="validate.php">
<label for="name">Enter Your Name:</label><br>
<input type="text" id="name" name="name"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Step 2: Create a PHP validation script and save it as validate.php.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve input data.
$name = trim($_POST["name"]);
// Check if the name field is empty.
if (empty($name)) {
echo "Error: Name field is required. You cannot leave it empty.";
} else {
echo "Success: You entered - " . $name;
}
}
?>In this example, when the user submits the form, data is sent to validate.php via POST method. The trim() function removes any leading or trailing whitespace from the input. The empty() function checks whether the input field is empty after trimming. If the user fill in the name and click on submit button, the result will be:
Output:
Success: You entered - John SmithIf the user leaves the name field empty and clicks the submit button, the result will be:
Output:
Error: Name field is required. You cannot leave it empty.
String Validation in PHP
String validation in PHP is the process of checking whether the input data contains only valid characters, such as alphabets and, optionally, white spaces—depending on your requirements. This is useful when you want to allow only names, usernames, or alphabet-only fields without numbers or special characters.
Let’s take an example where we create a PHP script to validate whether the name contains only alphabets and spaces. We will use the same HTML form from the previous example that accepts a name as a string.
Example 2: Validate String (Only Letters and Spaces)
Step 2: PHP Script (validate.php)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]);
// Check if name is empty.
if (empty($name)) {
$errMsg = "Error: Name field is required. Name cannot be empty.";
echo $errMsg;
}
// Validate that name contains only letters and spaces.
elseif (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$errMsg = "Error: Only alphabets and white space are allowed in the name.";
echo $errMsg;
} else {
echo "Success: You entered - " . $name;
}
}
?>
In the above PHP script, the trim() function removes extra spaces from the beginning and end.
What is preg_match() in PHP?
The preg_match() function is built-in function provided by PHP, which is used to perform pattern matching using regular expressions. This function checks whether a string matches a specific pattern or not.
If a match is found, it returns 1 (true). Otherwise, it returns 0 (false). If an error occurred, this function returns FALSE. We commonly use it for input validation, such as validating names, emails, phone numbers, passwords, etc. The general syntax of this function is as:
preg_match(pattern, input, matches)In the above syntax, there are three parameters. They are:
- pattern: This represents a regular expression pattern and must start and end with a forward slash (/).
- input: This is the input string that will be checked against the pattern.
- matches: This optional parameter represents an array that stores the matched results if a match is found.
In the line !preg_match(“/^[a-zA-Z ]*$/”, $name), the special characters ^ and $ mark the start and end of the string, respectively. The pattern [a-zA-Z ]* means that the string can contain any combination of uppercase or lowercase letters (a–z, A–Z) and spaces. So, “John Smith” is valid, but “John123” or “John@” is not.
Output:
Input: blank
Error: Name field is required. Name cannot be empty.
Input: John Smith
Success: You entered - John Smith
Input: John1234
Error: Only alphabets and white space are allowed in the name.
When to Use String Validation in PHP?
You can use string validation in PHP when you want to:
- Accept names such as first name and last name.
- Validate alphabet-only usernames.
- Avoid numeric or special characters in a field.
Validate Numbers in PHP
Number validation in PHP is the process of checking whether the input data contains only numeric values, such as integers or floating-point numbers. For example, if the mobile number field does not receive the numeric data from the user, the PHP code will display an error message. Number validation is useful for validating:
- Mobile numbers
- Age fields
- Price/amount
- Quantity
- Any field that requires numeric input
Validate Phone Number in PHP
A valid phone number typically consists of:
- Only digits (0–9)
- A fixed length (commonly 10 digits)
- No special characters (like @, #, !, etc.)
We can use preg_match() function to create a pattern for this.
Example 3:
Step 1: HTML Form (form.html)
<!DOCTYPE html>
<html>
<head>
<title>Phone Number Validation</title>
</head>
<body>
<form method="post" action="validate.php">
Enter Your Phone Number: <input type="text" name="phone"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Step 2: PHP Script (validate.php)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$phone = trim($_POST["phone"]);
// Check if phone number is empty.
if (empty($phone)) {
echo "Error: Phone number is required.";
}
// Validate phone number consisting of only digits and exactly 10 characters.
elseif(!preg_match("/^[0-9]{10}$/", $phone)) {
echo "Error: Phone number must be exactly 10 digits with no spaces or symbols.";
} else {
echo "Your phone number is " . $phone;
}
}
?>Output:
Input: Empty
Error: Phone number is required.
Input: 9876543210
Your phone number is 9876543210
Input: 98765-43210
Error: Phone number must be exactly 10 digits with no spaces or symbols.
Validate Age (Integer)
Example 4:
Step 1: Create an HTML form containing age input field and save it as form.html.
<!DOCTYPE html>
<html>
<head>
<title>Integer Number Validation</title>
</head>
<body>
<form method="post" action="validate.php">
Enter Your Age: <input type="text" name="age"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Step 2: Create a PHP script to validate age (validate.php)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$age = trim($_POST["age"]);
// Check if age field is empty.
if (empty($age)) {
echo "Error: Age field is required.";
}
// Validate if the age is an integer.
elseif (!filter_var($age, FILTER_VALIDATE_INT)) {
echo "Error: Age must be a valid integer.";
} else {
echo "Your age is " . $age;
}
}
?>In the above PHP script, we have used the filter_var() function, which is a built-in PHP function used to validate and sanitize data. The general syntax of this function is as:
filter_var(variable, filter, options)In the above syntax, the function accepts three parameters:
- variable: This parameter represents the value or input data you want to validate or sanitize.
- filter: This parameter represents the type of filter to apply, such as:
- FILTER_VALIDATE_INT
- FILTER_VALIDATE_EMAIL
- FILTER_VALIDATE_URL
- FILTER_VALIDATE_FLOAT
- options: This is an optional parameter which represents an associative array to define options like range, flags, etc.
The function returns the integer value if the input is valid. Otherwise, it returns false if the input is not a valid integer. The FILTER_VALIDATE_INT is a predefined PHP filter used to check if the value is a valid integer (whole number).
Output:
Input: Empty
Error: Age field is required.
Input: 35
Your age is 25
Input: 35.5
Error: Age must be a valid integer.
Validate Decimal Numbers
We can also validate decimal or floating-point numbers in PHP. Let’s write PHP script to validate price.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$price = $_POST["price"];
if (!filter_var($price, FILTER_VALIDATE_FLOAT)) {
echo "Error: Price must be a valid number.";
} else {
echo "Price is valid.";
}
}
?>In the above PHP script, the FILTER_VALIDATE_FLOAT is a predefined variable which validates decimal/floating-point numbers.
Best Practices for PHP Validation
There are some key points for PHP validation that you should remember them. They are:
- Always sanitize before validating.
- Use server-side validation even if JavaScript validation is present.
- Provide meaningful error messages.
- Use built-in PHP filters when available.
- Reuse code using functions or classes.
- Validate all user inputs through GET, POST, FILE, etc.
- Use libraries for complex validation rules.

