Tuesday, May 4, 2010

1:07 AM

you’ve been asking why this person has posted the same stuff which you can find easily in google. Ya you are right you can get lots of scripts but many of them are not useful for me so far. They just validate the email like “info@yahoo.com” but they didn’t validate the email address like “contact@roshanbh.com.np” or even the address like info@holmesglen.vic.edu.au“.


So I’m posting a email add validation function in PHP which validate those kind of address as well.

Function to validate email address in PHP

function validateEmail($email)
{
   if(eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$', $email))
      return true;
   else
      return false;
}

Let’s see the explanation of the following regular expression to validate email address in php

^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$

The “^” sign represents the start of the string.And, [a-zA-Z0-9._-]+ represents the first part of string before “@” sign can consists alpha bates, digits and “.,-” and “_” signs. After that “@” refers that this sign must exist. The next part is name of the domain and “[a-zA-Z0-9-]+” allow alpha bates, digits and “-” sign. After that period(.) should exist and validated by “\.“. And, the next string is TLD or ccTLd so can contain only two to four alphabates and validated by “[a-zA-Z]{2,4}“. The next part of expression “(\.[a-zA-Z]{2,3})?” refers that there will be another two or three alphabates after period(.) but this part is optional which is represented by “?” sign. And the last part is same as previous part and is optional as well.
Benefits:
Thus, this function validate the domain name that ends with .com or com.np or .vic.com.au . Furthermore, this function doesn’t accept the string like “info@homs.edu.” but I’ve some function which accepts the email which ends with period(.).


0 comments: