【问题标题】:Use pattern to validate email addresses使用模式验证电子邮件地址
【发布时间】:2019-05-07 15:35:30
【问题描述】:

你会使用类似的东西;

<input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">

因此,如果您理论上只允许使用域和子域;

<input type="email" name="email" pattern="[a-z0-9._%+-]+@[example]+\.[com]{2,}/@[subdomain]+\.[example].\[com]$">

我只想允许来自example.comsubdomain.example.com 的电子邮件回复,或者只允许以.co.uk 结尾的电子邮件回复,这是最理想的。

任何帮助将不胜感激。

UPDATE

使用;

pattern="[a-zA-Z0-9-]+@sub.example.co.uk" 表示验证将起作用。

但使用:

pattern="[a-zA-Z0-9-]+@sub.example.co.uk|+@example.co.uk" 表示验证将起作用,但也允许@gmail.com 等域。

UPDATE

这是表单的代码。

<form action="./login.php" method="post">
<input type="email" id="email" minlength="13" maxlength="29" pattern="[a-zA-Z0-9-]+@subdomain@example.co.uk|+@example.co.uk" style="text-transform: lowercase" placeholder="Enter your email address." name="email" required=""><br>
<input type="submit">
</form>

理想情况下,我可以设置允许的域和特定电子邮件地址的列表,因此只有 jon@example.co.ukigor@example.co.ukstephen@example.co.uk 可以提交。您能否将电子邮件的开头匹配为数组或$allowedaddresses 格式的整个内容,以节省从域中爆炸@

【问题讨论】:

标签: php html regex validation email


【解决方案1】:
  1. 不要尝试编写正则表达式来验证电子邮件地址,因为it's virtually impossible。管理电子邮件地址的标准定义非常松散,从历史上看,人们采用了许多截然不同的方式。
  2. 不要尝试将过多的应用程序逻辑打包到正则表达式中。

由于您只是尝试匹配域名,而这通常是电子邮件地址中唯一可靠的部分,因此您只需将字符串的结尾与正则表达式进行匹配即可。

$allowed_domains = [
    '.co.uk',
    'bar.co.uk'
];

$forbidden_domains = [
    'baz.bar.co.uk'    
];

// make it a bit easier to manage the lists of allowed/forbidden domains
function domain_suffix_to_regex($suffix) {
    return sprintf('/.*%s$/', preg_quote($suffix));
}
$allowed = array_map('domain_suffix_to_regex', $allowed_domains);
$forbidden = array_map('domain_suffix_to_regex', $forbidden_domains);

$emails = [
    'example@foo.bar.co.uk',
    'example@bar.co.uk',
    'example@baz.bar.co.uk'
];

foreach($emails as $email) {
    $permitted = false;
    foreach($allowed as $expr) {
        if( preg_match($expr, $email) ) {
            $permitted = true;
            echo "$email allowed by expr: $expr\n";
            break;
        }
    }
    if( $permitted ) {
        foreach($forbidden as $expr) {
           if( preg_match($expr, $email) ) {
                $permitted = false;
                echo "$email forbidden by expr: $expr\n";
                break;
           }
        }
    }
    var_dump($permitted);
}

输出:

example@foo.bar.co.uk allowed by expr: /.*\.co\.uk$/
bool(true)
example@bar.co.uk allowed by expr: /.*\.co\.uk$/
bool(true)
example@baz.bar.co.uk allowed by expr: /.*\.co\.uk$/
example@baz.bar.co.uk forbidden by expr: /.*baz\.bar\.co\.uk$/
bool(false)

【讨论】:

  • 谢谢。我将如何将其与表单结合起来,例如添加到问题中。
  • 哦。呃……不要。 1. 您必须使用 javascript 来增加复杂性,即便如此,这只是对最终用户的礼貌,因为... 2. 您仍然需要在服务器端进行验证,因为 HTML 表单提供零实际容量对发送到服务器的内容执行任何规则。
  • 是的,我知道@sammitch,我已经更新了问题:)
猜你喜欢
  • 2014-06-12
  • 1970-01-01
  • 2021-10-20
  • 2018-12-12
  • 1970-01-01
  • 2018-03-13
  • 2011-09-02
  • 2013-02-20
  • 2014-03-12
相关资源
最近更新 更多