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
Selected Reading
FILTER_VALIDATE_EMAIL constant in PHP
The FILTER_VALIDATE_EMAIL constant is used with PHP's filter_var() function to validate email addresses. It checks if an email follows the standard email format and returns the email if valid, or false if invalid.
Syntax
filter_var($email, FILTER_VALIDATE_EMAIL)
Return Value
Returns the validated email address on success, or false on failure.
Example
Here's how to validate an email address using FILTER_VALIDATE_EMAIL −
<?php
$myEmail = "example@demo.com";
if (filter_var($myEmail, FILTER_VALIDATE_EMAIL)) {
echo "$myEmail = valid email address";
} else {
echo "$myEmail = invalid email address";
}
?>
example@demo.com = valid email address
Testing Invalid Emails
Let's test with various invalid email formats −
<?php
$emails = [
"valid@example.com",
"invalid.email",
"@missinglocal.com",
"missing@.com",
"spaces @example.com"
];
foreach ($emails as $email) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "$email is VALID<br>";
} else {
echo "$email is INVALID<br>";
}
}
?>
valid@example.com is VALID invalid.email is INVALID @missinglocal.com is INVALID missing@.com is INVALID spaces @example.com is INVALID
Conclusion
FILTER_VALIDATE_EMAIL provides a reliable way to validate email addresses in PHP. It returns the email if valid or false if invalid, making it perfect for form validation and data processing.
Advertisements
