PHP

Validating Email Addresses

Checking whether a string contains a valid email address is two things at once: very common and very complicated.

Validating Email Addresses
function checkEmail($s) {
  $lastDot = strrpos($s, '.');
  $ampersat = strrpos($s, '@');
  $length = strlen($s);
  return !(
    $lastDot === false ||
    $ampersat === false ||
    $length === false ||
    $lastDot - $ampersat < 3 ||
    $length - $lastDot < 3
  );
}

Validating email addresses is difficult because the rules for valid domain names differ drastically between countries. For instance, bn.com is valid, whereas bn.de is not (but db.de is). Also, did you know that username@[127.0.0.1] is a valid email address (if 127.0.0.1 is the IP address of the mail server)?

Therefore, the recommendation is to only check for the major elements of an email address: valid characters (an @ character) and a dot somewhere after that. It is impossible to be 100% sure with checking email addressesif the test is too strict, the user just provides a fantasy email address. The only purpose of email checking is to provide assistance when an (unintentional) typo occurs.

Of course, this is also possible using regular expressions, but this is probably just slower. You should also be aware that the aforementioned code cannot detect every email address that is incorrect. Also watch out for the new international domains with special characters such as ä or é in it. Most regular expressions omit these, so you are much better off with the preceding code.

by BrainBellupdated
Advertisement: