0
0
PHPprogramming~5 mins

Common validation patterns in PHP

Choose your learning style9 modes available
Introduction

Validation helps check if data is correct before using it. It stops mistakes and keeps programs safe.

When a user fills a form and you want to check if the email looks right.
When you want to make sure a password is strong enough.
When you need to confirm a number is within a certain range.
When you want to check if a required field is not empty.
When you want to verify a date is in the correct format.
Syntax
PHP
<?php
// Example of validating an email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // valid email
} else {
    // invalid email
}
?>
Use PHP's built-in filter_var function for common validations like email and URL.
You can use regular expressions with preg_match for custom patterns.
Examples
This checks if the email is in a correct format.
PHP
<?php
// Validate email
$email = 'user@example.com';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo 'Valid email';
} else {
    echo 'Invalid email';
}
This checks if a number is between 18 and 99.
PHP
<?php
// Validate number range
$age = 25;
if ($age >= 18 && $age <= 99) {
    echo 'Age is valid';
} else {
    echo 'Age is invalid';
}
This checks if the name is not empty.
PHP
<?php
// Validate non-empty string
$name = 'John';
if (!empty($name)) {
    echo 'Name is provided';
} else {
    echo 'Name is missing';
}
This checks if the phone number matches the pattern 123-456-7890.
PHP
<?php
// Validate pattern with regex
$phone = '123-456-7890';
if (preg_match('/^\d{3}-\d{3}-\d{4}$/', $phone)) {
    echo 'Phone number is valid';
} else {
    echo 'Phone number is invalid';
}
Sample Program

This program checks if the email is correct, password is at least 8 characters, and age is between 18 and 99.

PHP
<?php
// Sample program to validate user input
$email = 'test@example.com';
$password = 'Pass1234';
$age = 20;

// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Email is invalid\n";
} else {
    echo "Email is valid\n";
}

// Validate password length
if (strlen($password) < 8) {
    echo "Password too short\n";
} else {
    echo "Password length is okay\n";
}

// Validate age range
if ($age < 18 || $age > 99) {
    echo "Age is invalid\n";
} else {
    echo "Age is valid\n";
}
OutputSuccess
Important Notes

Always sanitize data before validating to avoid security issues.

Use built-in PHP filters when possible for simplicity and reliability.

Regular expressions are powerful but can be tricky; test them carefully.

Summary

Validation checks if data is correct before using it.

Use filter_var for common checks like email and URL.

Use preg_match for custom pattern checks.