PHP valid email format checker function

Discussion in 'PHP' started by norfstar, Jan 12, 2010.

  1. #1
    I have been using this function for years to check email address format validity:

    function is_email_valid($var){
    	if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $var)) {
    		return TRUE;
    	} else {
    		return FALSE;
    	}
    }
    PHP:
    But it seems that at some point since then, TLDs with just one character (for example, q.com) have started being used, and email addresses at these are being deduced to be invalid by this function. Can anyone modify the above code so an address like would pass?
     
    norfstar, Jan 12, 2010 IP
  2. astkboy2008

    astkboy2008 Peon

    Messages:
    211
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #2
    see this class its check if the email domian is exsist
    EAValidator
    How to Work?

    * check length of email address max is 320 characters where:
    64 characters max for the user of email address 1 character max for the @ 255 characters max for the host name
    * apply regular expressions to valid email addres string
    * check if exist host to send messages to email address
     
    astkboy2008, Jan 12, 2010 IP
  3. Steve136

    Steve136 Peon

    Messages:
    240
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hi

    Try this function:
    
    <?php
    	function isValidEmail($email){
    		if (preg_match("/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.([a-z][a-z]+)|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i", $email)) {
    			return true;
    		}
    		return false;
    	}
    
    	if(isValidEmail('name@x.com')) {
    		echo "Email address is VALID.";
    	} else {
    		echo "Email address is INVALID";
    	}
    ?>
    PHP:
    Regards,

    Steve
     
    Steve136, Jan 12, 2010 IP
    norfstar likes this.
  4. norfstar

    norfstar Peon

    Messages:
    1,154
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Thanks Steve, that works fine :).
     
    norfstar, Jan 12, 2010 IP
  5. JAY6390

    JAY6390 Peon

    Messages:
    918
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Better still forget the massive regular expressions etc and just use the built in filter_var function with the FILTER_VALIDATE_EMAIL type
    if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
      // EMAIL OK
    }else{
      // EMAIL INVALID
    }
    PHP:
    Thats far easier and is guaranteed to be correct every time
     
    JAY6390, Jan 12, 2010 IP