PHP Form Validation
Ensuring user input is safe and correct
๐ What is Form Validation?
Form validation checks user input to ensure data is correct, complete, and safe before processing. It protects your application from invalid or malicious data and improves user experience.
<?php
// Basic validation example
$name = $_POST['name'];
if (empty($name)) {
echo "Name is required!";
}
?>
Key Validation Concepts
Empty Check
Verify fields are not empty
<?php
if (empty($name)) {
$error = "Required";
}
?>
Text Validation
Check if input contains only letters
<?php
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$error = "Only letters allowed";
}
?>
Sanitization
Remove unwanted characters from input
<?php
$name = htmlspecialchars($name);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
?>
Security
Protect against malicious input
<?php
$safe = strip_tags($input);
$safe = trim($safe);
?>
๐น Basic Validation Example
Validating a simple name field with error messages:
<?php
$name = "";
$nameErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// Check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name">
<span style="color:red;">* <?php echo $nameErr; ?></span>
<input type="submit" value="Submit">
</form>
๐น Validating Multiple Fields
Complete form validation with name, email, and website fields:
<?php
$name = $email = $website = "";
$nameErr = $emailErr = $websiteErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Name validation
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
// Email validation
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
// Website validation
if (!empty($_POST["website"])) {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $website)) {
$websiteErr = "Invalid URL";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
๐น Common Validation Functions
PHP provides built-in functions for validation:
๐ธ Filter Functions
<?php
// Validate email
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
}
// Validate URL
$url = "https://example.com";
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo "Valid URL";
}
// Validate integer
$number = "123";
if (filter_var($number, FILTER_VALIDATE_INT)) {
echo "Valid integer";
}
// Sanitize string
$string = "<script>alert('xss')</script>";
$clean = filter_var($string, FILTER_SANITIZE_STRING);
echo $clean; // Outputs: alert('xss')
?>
๐น Regular Expression Validation
Using regex patterns for custom validation rules:
<?php
// Phone number validation (US format)
$phone = "123-456-7890";
if (preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/", $phone)) {
echo "Valid phone number";
}
// Postal code validation
$zip = "12345";
if (preg_match("/^[0-9]{5}$/", $zip)) {
echo "Valid ZIP code";
}
// Username validation (alphanumeric, 3-16 chars)
$username = "user123";
if (preg_match("/^[a-zA-Z0-9]{3,16}$/", $username)) {
echo "Valid username";
}
?>
๐น Displaying Validation Errors
Show error messages next to form fields for better user experience:
<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form Validation</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
<span class="error">* <?php echo $nameErr; ?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email; ?>">
<span class="error">* <?php echo $emailErr; ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>