Data Validation in PHP: Complete Guide with Code Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Data Validation in PHP: From Simple Checks to Professional Solutions



Data validation is one of the cornerstones of a secure and stable web application. PHP provides many built-in tools for efficiently checking user input. In this article, we will cover the main approaches, from simple functions to powerful libraries, and show practical examples.



Why is Validation Needed?

Any application that accepts data from the user (forms, API, URL parameters) must verify its correctness. This helps:

  • Prevent SQL injections and XSS attacks
  • Ensure data integrity in the database
  • Improve user experience (clear error messages)
  • Avoid logical errors in application operation


Built-in PHP Validation Functions

PHP provides several simple but effective functions for basic data checking:



1. Checking for Emptiness: empty() and isset()

// Check that a field is not empty$name = trim($_POST['name'] ?? '');if (empty($name)) {    echo "Name is required";}

// Check if a variable existsif (!isset($_POST['email'])) { echo "Email field was not submitted";}


2. Filters: filter_var()

This is perhaps the most convenient built-in mechanism for validating common data types:

$email = "user@example.com";if (filter_var($email, FILTER_VALIDATE_EMAIL)) {    echo "Email is valid";} else {    echo "Invalid email format";}

// Other useful filters:$url = "https://pythonlib.ru";if (filter_var($url, FILTER_VALIDATE_URL)) { echo "URL is valid";}

$ip = "192.168.1.1";if (filter_var($ip, FILTER_VALIDATE_IP)) { echo "IP address is valid";}

// Filter for integers$age = 25;if (filter_var($age, FILTER_VALIDATE_INT, ["options" => ["min_range" => 1, "max_range" => 120]])) { echo "Age is valid";}


Regular Expressions for Complex Validation

When standard filters are not enough, regular expressions come to the rescue. The preg_match() function allows you to check data against any pattern:

// Phone number validation (Russian format)$phone = "+7 (999) 123-45-67";$pattern = '/^\\+7\\s?\\(\\d{3}\\)\\s?\\d{3}-\\d{2}-\\d{2}$/';if (preg_match($pattern, $phone)) {    echo "Phone number is valid";} else {    echo "Invalid phone number format";}

// Password validation (minimum 8 characters, at least one digit and one letter)$password = "MyPass123";$pattern = '/^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$/';if (preg_match($pattern, $password)) { echo "Password is strong";} else { echo "Password does not meet requirements";}


Validation Libraries: When the Project Gets More Complex

For large projects (frameworks, CMS), manual validation becomes inconvenient. Specialized libraries come to the rescue. Let's look at two of the most popular ones:



1. Symfony Validator

Part of the Symfony ecosystem, but can be used standalone. It allows you to describe validation rules via annotations or YAML/XML:

use Symfony\\Component\\Validator\\Validation;use Symfony\\Component\\Validator\\Constraints as Assert;

class User { /** * @Assert\\NotBlank(message="Name cannot be empty") * @Assert\\Length(min=2, max=50) */ public $name; /** * @Assert\\Email(message="Invalid email format") */ public $email;}

// Usage$validator = Validation::createValidatorBuilder() ->enableAnnotationMapping() ->getValidator();

$user = new User();$user->name = "A";$user->email = "invalid-email";

$errors = $validator->validate($user);if (count($errors) > 0) { foreach ($errors as $error) { echo $error->getMessage() . "<br>"; }}

Recommendations