Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to validate an email address in PHP ?
In PHP, validating email addresses is essential for ensuring data integrity and preventing invalid inputs. PHP provides several methods to validate email addresses, from built-in functions to custom regular expressions.
Using filter_var() Function
The most recommended approach is using PHP's built-in filter_var() function with the FILTER_VALIDATE_EMAIL filter −
<?php
$email = "pattrick@tutorialspoint.com";
// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "$email is a valid email address";
} else {
echo "$email is not a valid email address";
}
?>
pattrick@tutorialspoint.com is a valid email address
Using Regular Expression with preg_match()
You can also create a custom validation function using regular expressions with preg_match() −
<?php
function validateEmail($email) {
$pattern = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix";
return preg_match($pattern, $email) ? true : false;
}
$email = "alex@tutorialspoint.com";
if (validateEmail($email)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
?>
Valid email address.
Testing Invalid Email Examples
Here's how both methods handle invalid email addresses −
<?php
$emails = [
"valid@example.com",
"invalid.email",
"@invalid.com",
"test@.com"
];
foreach ($emails as $email) {
echo "Email: $email - ";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid
";
} else {
echo "Invalid
";
}
}
?>
Email: valid@example.com - Valid Email: invalid.email - Invalid Email: @invalid.com - Invalid Email: test@.com - Invalid
Comparison
| Method | Ease of Use | Performance | Recommended |
|---|---|---|---|
filter_var() |
Very Easy | Fast | Yes |
preg_match() |
Moderate | Slower | For custom patterns |
Conclusion
Use filter_var() with FILTER_VALIDATE_EMAIL for standard email validation as it's built-in, reliable, and follows RFC standards. Custom regex patterns with preg_match() are useful when you need specific validation rules.
