Search code examples
phpstringemailkeypreg-match

php only allow letters but doesnt work on @, - etc


I've added a form to my website to subscribe to my newsletter. The problem is, I use the first_name tag for email address but it doesn't allow @ or #.

$first_name = $_POST['first_name']; // required 
$email_address = $_POST['email_address']; // required     

$error_message = ""; 
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

$string_exp = "/^[A-Za-z .'-]+$/";

if(!preg_match($string_exp,$first_name)) { 
      $error_message .= 'The First Name you entered does not appear to be valid.<br />'; 
}

Also I want the email address allow to use keys as @ or #.


Solution

  • Your regex for first_name is

    $string_exp = "/^[A-Za-z .'-]+$/";
    

    Which restricts you to only latin characters, space, period, single quote and dash.

    If you wanted to allow @ and # then you should add these as extra characters to the allowable character list:

    $string_exp = "/^[A-Za-z .'@#-]+$/";
    

    Important: you must to add these before the last - or the - will be interpreted as specifying a character range.

    A better question though is why are you restricting the user's name at all? If someone has a non-ANSI character in their name (eg russian, chinese, japanese, korean or even accented latin characters) then you will prevent them from signing up. A user's name should really have no restrictions at all, and if you have issues with other characters then there is a bug in the code that generates any emails.

    Repeat this for the email allowable character lists (remembering to put them before any - at the end)

    A final comment: Your regex for email addresses has much bigger problems than these characters. Most obviously it will prevent legitimate GTLDs that are longer than 4 characters at the end from working (eg .museum), or the + symbol before the @ (very useful with gmail addresses).

    A fully compliant regular expression for parsing email addresses is extremely complicated (see http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html). I generally use the regex specified in the HTML5 spec (https://www.w3.org/TR/html5/forms.html#valid-e-mail-address) since this will be the one the browser also uses for <input type="email"> but there are many alternatives (see Using a regular expression to validate an email address)

    Email regex in html5 spec:

    /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/