Code working, but is there a better way???

Discussion in 'PHP' started by ian_ok, Feb 9, 2007.

  1. #1
    I want to check certain data entry fields to make sure an @ is present and if not show an error.

    Is this code OK or should I do it a different way.

    NOTE I only want to check that the field has the @ nothing else.

    function validate_email($d) {
      $missing = array('@');
      foreach ($missing as $c)
        if (strpos($d, $c) !== false) return true;
      return false;
    }
    
    if  (!validate_email($_POST['from'])) {
    echo "Error";
    }
    PHP:
    Thanks Ian
     
    ian_ok, Feb 9, 2007 IP
  2. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #2
    
    function validate_email( $email )
    {
    if(preg_match("/@/si", $email)) : return true; endif;
    }
    
    PHP:
    a more complicated regex would be preferred, if you want something to properly check address formats then holla ....
     
    krakjoe, Feb 9, 2007 IP
  3. ian_ok

    ian_ok Peon

    Messages:
    551
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hi Joe,

    What's the 'si' for???

    Ian
     
    ian_ok, Feb 9, 2007 IP
  4. TwistMyArm

    TwistMyArm Peon

    Messages:
    931
    Likes Received:
    44
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I believe the 'i' means 'search without case sensitivity' and the 's' means 'allow new lines' (basically).

    You could also use strpos... something like:
    $found = strpos( $email, '@' );

    Note that because strpos can return '0' (meaning it found the '@' right at the start of the string) you need to compare $found with a triple equal sign against false.

    So, your function could be:
    
    function validate_email( $email ) {
        $found = strpos( $email, '@' );
        if ( $found === FALSE ) {
            return FALSE;
        } else {
            return TRUE;
        }
    }
    
    PHP:
     
    TwistMyArm, Feb 9, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    I use this function to validate emails.
    
    
    function is_valid_email($email)
    {
    	return preg_match('/^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$/si', $email);
    }
    
    
    PHP:
     
    nico_swd, Feb 9, 2007 IP