How to validate an email address
Short answer
filter_var() returns the address if it is valid and false if not:
<?php
var_dump(filter_var('anna@example.com', FILTER_VALIDATE_EMAIL) !== false);
var_dump(filter_var('anna@example', FILTER_VALIDATE_EMAIL) !== false);Output:
bool(true)
bool(false)Before saving
Trim the spaces and lowercase the address so that the same address is not saved twice:
<?php
$email = strtolower(trim(' Anna@Example.COM '));
echo $email;Output:
anna@example.comWhat the check does not guarantee
A valid format does not mean the mailbox exists. There is only one way to be sure — send an email with a confirmation link.
Functions used in this recipe
- filter_var — Validates or sanitises a value by a given rule.
- trim — Removes whitespace and other characters from both ends of a string.
- strtolower — Converts ASCII letters to lowercase.