开发者

Using regex for simple email validation [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

What is the best regular expression for validating email addresses?

Is there a php library for email address validation?

On my register form a user will add his email and then get an email to verify his account. However I want to have a simple email validation and I would like to know if the following is appropriate.

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

if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {开发者_运维知识库

  echo "Valid email address.";
}

else {

  echo "Invalid email address.";
}
?>


Try:

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo 'Valid';
} else {
  echo 'Invalid';
}


Your regular expression unnecessarily forbids subdomains, such as user@unit.company.com. Additionally, you shouldn't use the deprecated eregi.

Instead of reinventing your own wheel, use filter_var:

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo "Valid email address.";
} else {
  echo "Invalid email address.";
}


Apart from a regex, you can also use filter_var:

if (filter_var('someone@example.com', FILTER_VALIDATE_EMAIL)) === false)
{
  echo "Invalid email address.";
}


Email validation is a bit tricky, because the RFC that specifies the format of email addresses is way more unrestrictive that people think. For example, the following are all valid email addresses:

  • "Abc@def"@example.com
  • "Fred Bloggs"@example.com
  • "Joe\Blow"@example.com
  • "Abc@def"@example.com
  • customer/department=shipping@example.com
  • $A12345@example.com
  • !def!xyz%abc@example.com
  • _somename@example.com

The correct regex for email validation seems to look something like this, which I won't even try to look into ;) However, when using PHP, you should really use filter_var(), like so:

$valid = filter_var($email, FILTER_VALIDATE_EMAIL);
# $valid will be TRUE if the email address was valid,
# otherwise FALSE.

RFC822 seems to contain the original email format specification, but I think that 2822 (as linked above) is just a revision / amendment of that original RFC.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜