Form validation is the process of checking submitted data before using or saving it. PHP performs server-side validation to ensure that required fields are filled in and that values have the expected format.
Form validation checks whether submitted information meets the application's requirements.
Common validation tasks include:
Example:
<?php
$name = "Rahul";
if (trim($name) === "") {
echo "Name is required.";
} else {
echo "Name is valid.";
}
?>
Name is valid.
Server-side validation is essential because browser validation can be bypassed.
A required field must contain a value before the form can be accepted.
<?php
$name = " ";
if (trim($name) === "") {
echo "Name is required.";
} else {
echo "Name accepted.";
}
?>
Name is required.
The trim() function removes whitespace
from the beginning and end of a string. This helps
prevent a user from submitting only spaces.
Another example:
<?php
$email = "";
if (trim($email) === "") {
echo "Email is required.";
}
?>
Email is required.
PHP provides filter_var() with
FILTER_VALIDATE_EMAIL to check whether
an email address has a valid format.
<?php
$email = "student@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
?>
Valid email address.
Invalid email example:
<?php
$email = "studentexample.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
?>
Invalid email address.
Email format validation does not prove that the mailbox exists. Applications may need an email verification process as well.
Use is_numeric() to check whether a value
is a number or a numeric string.
<?php
$age = "21";
if (is_numeric($age)) {
echo "Age is numeric.";
} else {
echo "Please enter a number.";
}
?>
Age is numeric.
Validate a range:
<?php
$age = 20;
if (
filter_var($age, FILTER_VALIDATE_INT) !== false &&
$age >= 1 &&
$age <= 120
) {
echo "Valid age.";
} else {
echo "Invalid age.";
}
?>
Valid age.
Range validation ensures that a value is not only numeric but also within the permitted limits.
If your application expects an Indian mobile number containing exactly 10 digits, you can validate its format using a regular expression.
<?php
$mobile = "9876543210";
if (preg_match('/^[0-9]{10}$/', $mobile)) {
echo "Mobile number format is valid.";
} else {
echo "Enter a 10-digit mobile number.";
}
?>
Mobile number format is valid.
Invalid example:
<?php
$mobile = "98765";
if (preg_match('/^[0-9]{10}$/', $mobile)) {
echo "Valid mobile number.";
} else {
echo "Invalid mobile number.";
}
?>
Invalid mobile number.
This checks the format only. It does not verify that the number is active or belongs to a particular person.
Never assume that a dropdown's submitted value is valid just because the browser displayed predefined options. A user can send a different value manually.
<?php
$course = $_POST['course'] ?? '';
$allowedCourses = [
'PHP',
'JavaScript',
'Python'
];
if (in_array($course, $allowedCourses, true)) {
echo "Selected course: " .
htmlspecialchars($course, ENT_QUOTES, 'UTF-8');
} else {
echo "Please select a valid course.";
}
?>
The submitted course is accepted only if it matches one of the allowed values.
Example form:
<form method="post" action="">
<label for="course">Choose Course:</label>
<select name="course" id="course" required>
<option value="">Select a course</option>
<option value="PHP">PHP</option>
<option value="JavaScript">JavaScript</option>
<option value="Python">Python</option>
</select>
<button type="submit">Submit</button>
</form>
You can check whether a password meets a minimum
length requirement using strlen().
<?php
$password = "mypassword123";
if (strlen($password) >= 8) {
echo "Password length is acceptable.";
} else {
echo "Password must contain at least 8 bytes.";
}
?>
Password length is acceptable.
For ordinary ASCII passwords, strlen()
counts bytes and corresponds to the number of
characters. For multibyte text, byte length and
character count can differ.
In a real application, validate password requirements
on the server and store passwords using
password_hash(), not as plain text.
Use password_verify() during login.
Save this example as
validation_form.php. It validates a
student's name, email, and mobile number on the server.
<?php
$name = '';
$email = '';
$mobile = '';
$errors = [];
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$mobile = trim($_POST['mobile'] ?? '');
// Validate name
if ($name === '') {
$errors[] = 'Name is required.';
} elseif (strlen($name) > 100) {
$errors[] = 'Name must not exceed 100 bytes.';
}
// Validate email
if ($email === '') {
$errors[] = 'Email is required.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Enter a valid email address.';
}
// Validate mobile
if (!preg_match('/^[0-9]{10}$/', $mobile)) {
$errors[] = 'Enter a valid 10-digit mobile number.';
}
if (count($errors) === 0) {
$success = 'Form submitted successfully.';
}
}
?>
<form method="post" action="">
<label for="name">Student Name:</label>
<input
type="text"
id="name"
name="name"
maxlength="100"
value="<?= htmlspecialchars(
$name,
ENT_QUOTES,
'UTF-8'
) ?>"
required
>
<br><br>
<label for="email">Email:</label>
<input
type="email"
id="email"
name="email"
value="<?= htmlspecialchars(
$email,
ENT_QUOTES,
'UTF-8'
) ?>"
required
>
<br><br>
<label for="mobile">Mobile Number:</label>
<input
type="tel"
id="mobile"
name="mobile"
pattern="[0-9]{10}"
maxlength="10"
value="<?= htmlspecialchars(
$mobile,
ENT_QUOTES,
'UTF-8'
) ?>"
required
>
<br><br>
<button type="submit">Submit Form</button>
</form>
<?php
if (count($errors) > 0) {
echo "<h4>Please correct these errors:</h4><ul>";
foreach ($errors as $error) {
echo "<li>" .
htmlspecialchars($error, ENT_QUOTES, 'UTF-8') .
"</li>";
}
echo "</ul>";
}
if ($success !== '') {
echo "<p>" .
htmlspecialchars($success, ENT_QUOTES, 'UTF-8') .
"</p>";
}
?>
The example collects validation errors and displays them together. It preserves the submitted values after validation fails.
For a production form that changes server data, add CSRF protection and use prepared statements when saving information to a database.
Validation and sanitization have different purposes.
Validation example:
<?php
$email = "student@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Email is valid.";
} else {
echo "Email is invalid.";
}
?>
Output escaping example:
<?php
$name = '<script>alert("Hello")</script>';
echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
?>
Escaping converts special characters so the string is displayed as text instead of being interpreted as HTML markup.
Do not rely on sanitization alone. Validate data according to business rules, escape output for its context, and use prepared statements for database queries.
filter_var().1. Which PHP function can validate an email format?
2. Why is server-side validation necessary?
3. Which function escapes special HTML characters?