0
function validateemail($email) {
$v = "/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/";

return (bool)preg_match($v, $email);
}
// check e-mail address, to see if it's a valid phone number
if ($validateemail($email)) {
$error = true;
echo 'Invalid phone number!';
}

I'm trying to check if an e-mail address is valid by the function validateemail, if it's an invalid phone number a message is displayed and $error is set to true. However I can't seem to get this code to work, there are no syntax errors as far as I know. Any advice would be appreciated.

BTW - I know there are other ways to validate e-mail addresses, this is for a college project and for that purpose we have to use regex.

Thanks in advance!

HavelTheGreat
  • 3,299
  • 2
  • 15
  • 34
Andrew
  • 45
  • 2
  • 7
  • 1
    For future readers who aren't doing this for a college project, please use [`filter_var($email, FILTER_VALIDATE_EMAIL)`](http://php.net/manual/en/filter.examples.validation.php). – Jason McCreary Mar 12 '15 at 15:38
  • 1
    Also found my answer on http://emailregex.com – devXen Mar 12 '15 at 16:42
  • Please note that all the regexes on emailregex.com do different things. The one under "Python" `r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"` is entirely different than the one labeled "Javascript" `/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[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`, etc. – Andy Lester Mar 12 '15 at 17:08

3 Answers3

0

You have - not in the final position inside the first [a-zA-Z0-9_-.+] group.

Try

[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z]+

Have a look at this example.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

You need to escape the dash as it can also be used to indicate a character range.

function validateemail($email) {
  $v = "/[a-zA-Z0-9_\-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/";
  return (bool)preg_match($v, $email);
}
Professor of programming
  • 2,978
  • 3
  • 30
  • 48
0

If you only want to check if it is a valide e-mail or not, I'd suggest filter_var($email, FILTER_VALIDATE_EMAIL, e.g.:

<?php
$email = "john.doe@example.com";

if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  echo("$email is a valid email address");
} else {
  echo("$email is not a valid email address");
}
?> 

Source: www.w3schools.com/php/filter_validate_email.asp

manniL
  • 7,157
  • 7
  • 46
  • 72