您将使用类似的内容
<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.com
和subdomain.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.uk
,igor@example.co.uk
和stephen@example.co.uk
可以提交。您可以将电子邮件的开头匹配为数组,还是将整个内容以$allowedaddresses
的格式进行匹配,以保存@
从域中爆炸出来。
答案 0 :(得分:0)
由于您只想尝试匹配域名,而域名通常是电子邮件地址中唯一可靠的合理部分,因此,您只需简单地将字符串的末尾与正则表达式匹配即可。
$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)