PHP Tutorial: Validating Email Addresses
|April 25, 2012||Posted by Greg Bulmash under PHP|
When you want to make sure an e-mail address is formatted correctly, a Google search will turn up a number of functions and preg/ereg regular expressions. But one of the easiest ways is to use a PHP function that has been a part of the standard PHP installation since 5.2:
It's as simple as:
$email = "email@example.com"; $isValid = filter_var($email, FILTER_VALIDATE_EMAIL);
$isValid will be a boolean value (true or false).
Worth noting is that if you read the discussion on the validation filters page, some people will claim that an address like
john@gmail will validate. I haven't found that to be the case, but I have found that while it requires at least a two part domain after the @, it's loose with how many characters it must be. Thus, while
john@gmail did not validate in my tests,
Because of the ever-evolving nature of the TLD (Top Level Domain) registration system, I don't consider this a bug. I consider it future proofing. While there aren't any single-letter or single-digit domains yet (to my knowledge), I'm sure someone will propose selling them off for a million bucks a pop and an internet land rush for dot-A and dot-B will commence.