我正在尝试编写一个注册表格,用于验证用于注册的电子邮件。
简而言之,我想确保用于注册的电子邮件ID是一个公司域,而不是像gmail或yahoo那样的东西。
我有以下代码来检查电子邮件是否是给定域的一部分,我如何修改它以检查它是否在给定的域列表中?(例如:gmail.com、yahoo.com、hotmail.com等)。
return (bool) preg_match('/^([a-z0-9'+'_'-'.]+)@([a-z0-9'+'_'-'.]{2,})('.[a-z]{2,4})$/i', $domain);
我认为应该是这样的,但不完全确定:
function validate($email)
{
$error = 0;
$domains = array('gmail.com','yahoo.com','hotmail.com');
foreach($domains as $key=>$value)
{
if(preg_match('/^([a-z0-9'+'_'-'.]+)@([a-z0-9'+'_'-'.]{2,})('.[a-z]{2,4})$/i', $value)
{
$error=1;
}
}
if($error==0)
return true;
else
return false;
编辑:我尝试了这里给出的所有答案,无论我使用哪个领域,表单提交都没有问题!(即使是非电子邮件似乎也有效!)
这就是我如何调用函数-
if(isset($_POST['clients_register']))
{
//Must contain only letters and numbers
if(!preg_match('/^[a-zA-Z0-9]$/', $_POST['name']))
{
$error[]='The username does not match the requirements';
}
//Password validation: must contain at least 1 letter and number. Allows characters !@#$% and be 8-15 characters
if(!preg_match('/^(?=.*'d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,15}$/', $_POST['password']))
{
$error[]='The password does not match the requirements';
}
//Email validation
if (validateEmail($_POST['email'])==false)
{
$error[]='Invalid E-mail';
}
//Output error in array as each line
if ( count($error) > 0)
{
foreach ($error as $output) {
echo "{$output} <br>";
}
} else {
//Syntax for SQL Insert into table and Redirect user to confirmation page
}
}
问题是,无论我做什么,用户都会被重定向到确认页面(即使是由数字和类似"表格"的电子邮件组成的名称。
您应该在单独的步骤中完成。首先检查电子邮件地址是否具有有效语法。然后提取域名,看看它是否不在你的黑名单中。
function validate($email)
{
if (!preg_match('/^([a-z0-9'+'_'-'.]+)@([a-z0-9'+'_'-'.]{2,})('.[a-z]{2,4})$/i', $email)) return false;
$domains = array('gmail.com','yahoo.com','hotmail.com');
list(, $email_domain) = explode('@', $email, 2);
return !in_array($email_domain, $domains);
}
function validateEmail($email)
{
// Etc, just an array of the blacklisted domains
$blacklistDomains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'googlemail.com'];
// Check if the email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
// Split the email after the '@' to get the domain
$emailParts = explode('@', $email);
if (in_array(end($emailParts), $blacklistDomains)) {
return false;
}
return true;
}
你需要一个相当大的域列表。
PHP
// Suposing that $email is a valid email
function validate($email) {
$invalidDomains = array('gmail.com','yahoo.com','hotmail.com');
$parts = explode('@',$email);
$domain = $parts[1];
if(!in_array($domain,$invalidDomains)) return true;
return false;
}
如果有用,请告诉我。