Search code examples
preg-matchemail-validation

!preg_match for email checking


I have this command to check for valid email address. I just found out that when I try to add this to our email server (all email requests off this form are local email addresses), the email server does not allow a numeric character to start the email address/username. I have read through all the documentation for the command preg_match and cannot find how to make it fail if it starts with a numeric in the first character location. I am a newbie so any help would be appreciated.

if (!preg_match("(^[-\w\.]+@([-a-z0-9]+\.)+[a-z]{2,4}$)i", $in_email))

Solution

  • Try this one;

    /^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/
    

    And use as follows

    $regex = '/^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
    
    if (preg_match($regex, $email)) {
        // Valid email
    } else { 
        // Invalid email
    }