【问题标题】:How do I restrict special characters except underscore, hyphen and dot in email field in PHP? [duplicate]如何在 PHP 的电子邮件字段中限制除下划线、连字符和点之外的特殊字符? [复制]
【发布时间】:2014-10-11 01:19:06
【问题描述】:

这是我的代码。

function emailField($email)
{
return filter_var($email, FILTER_VALIDATE_EMAIL);   
}

if(emailField($_POST['email'])=='')
  {
    echo "Invalid email";
  }
  else
  {
  echo "Valid";
  }

这允许所有特殊字符。我只想允许下划线、连字符和点。如何避免?

【问题讨论】:

  • 为什么要避免使用有效的电子邮件? filter_varFILTER_VALIDATE_EMAIL 仅验证 有效 电子邮件。进一步限制它意味着禁止有效电子邮件。
  • 此字符在电子邮件地址中完全有效。

标签: php email-validation


【解决方案1】:

像这样使用正则表达式:

/^[\w\.]+@/

那么你还应该检查域是否真的存在。

PHP:

$regex = "/^[\w\.]+@/";
$email = emailField($_POST['email']);

$domain = preg_replace($regex, '', $email); //get the domain of the email address by removing the local-part

//Using checkdnsrr we are checking if this domain is registred
if($email == '' && preg_match($regex, $email) && checkdnsrr($domain)){
  echo "Valid";
}

另请参阅:http://php.net/manual/en/function.checkdnsrr.php

【讨论】:

  • \w 包括下划线和数字字符,因此您可以在表达式中省略 \d 和 _。由 \w 匹配的字符也可能取决于语言环境。
【解决方案2】:

同时使用复杂的filter_var 验证和简单的preg_match 验证。

function validate_email_popularly($email) {
    return
        filter_var($email, FILTER_VALIDATE_EMAIL)
        && preg_match('/\A[\w.-]*+@[\w.-]*+\z/', $email)
    ;
}

您还应该使用filter_input 而不是$_POST。此函数可以将意外的Notice: Undefined indexArray 过滤成False

$email = filter_input(INPUT_POST, 'email');
echo validate_email_popularly($email) ? 'Valid' : 'Invalid';

【讨论】:

猜你喜欢
  • 2013-01-11
  • 2014-02-12
  • 1970-01-01
  • 2022-12-16
  • 2023-03-19
  • 1970-01-01
  • 2021-09-14
  • 2017-06-15
  • 1970-01-01
相关资源
最近更新 更多