Saturday, 3 December 2011

PHP: Validating email address.

function emailValidate($email)
{
   if(!eregi("^[a-z]+[a-z0-9_-]*(\.[a-z0-9_-]+)*@[a-z0-9]+
      (\.[a-z0-9_-]+)*\.(\.[a-z]+){2,}$",$email))
  {
      return true;
  }
  return false;
}

eregi case insensitive regular expression math.

Find more about eregi function here
emailValidate function returns true if the email matches with regular expression else returns false.
eregis function returns 0 if expression doesn't match.

In our case, according to regular expression, the email address has to follow the "example@mail.com" form.
Of course you can change the expression as your wish.

Explanation of the expression:
^ indicates the beginning of the expression, therefore
^[a-z]+[a-z0-9_-]*  means the email address must started with one or more alphabets and followed by alphabets or numbers or "_" or -.
* (star) indicates 0 or more.

\. : \ (backslash) indicates that whatever follows backslash, that symbol will appear exactly as it is.
([a-z]+){2,}$ : $(dollar) indicates that end of the expression.
{2,} indicates the number of occurrences. Omitting second number means that at least 2 characters have to be there. If it was {2, 4}, number of occurrences should be at least 2 and at most 4 characters.

No comments:

Post a Comment