Just came up with a fairly smart way to validate email that removes a few issues generally caused by this sort of stuff. It’s not totally complete and it’s obviously part of a validation class – anybody planning on using it will need to modify it to make it work to their needs.

I return a value so the class which calls this can replace the value back in the form if there is an error, and it actually replaces it in the data that is used (sent to the DB or whatever), I also use a custom validation exception class, these are all things that will need to be considered if anybody who sees it plans on using. Caveat emptor and whatnot.

What it does is sends the value to the PHP filter functions for validating as looking remotely like an email address, which is handy but it will validate local addresses and for domains that don’t exist.

What my code does is check if there is a remote address part and then if it is an IP just allows it, if it’s a domain it checks if the domain has MX records using checkdnsrr() – if that’s all good it allows it.

What could be improved? It doesn’t work so well at preventing local IP addresses going through. It also won’t tell you if the user is legit at a given domain or if the user has any association at all, so address validation will be a must in some circumstances, but it will prevent the standard dfgdf@dfdgdf.com type stuff. At least you’ll know if the domain part looks even close to reasonable, which is one of the ‘failings’ (read: missing features?) of FILTER_VALIDATE_EMAIL if you want internet-only addresses entering.

	public function email_address($value) {
		$result = filter_var($value, FILTER_VALIDATE_EMAIL);
		if($result == false) {
			throw new validateException("Invalid email address");
		}
		$domain = explode("@", $value, 2);
		if(filter_var($domain[1], FILTER_VALIDATE_IP) !== false) {
			return $value;
		}
		if(checkdnsrr($domain[1]) == false) {
			throw new validateException("Email domain doesn't seem to exist or is incapable of recieving mail");
		}
		return $value;
	}

« »