注册不同的电子邮件类型

时间:2018-06-08 13:03:06

标签: php

我希望用户使用他们的学生电子邮件地址进行注册,我的代码仅适用于一所大学,我想拥有6所不同的大学。

        if(!preg_match('/^x[\d]{8}@student\.ncirl\.ie$/', $email)){ // forcing exact email
            // Return Error - Invalid Email
            $error = true;
            $emailError = 'The email you have entered is invalid, please try again.';
        } 
        else{
            // check email exist or not
            $res = $conn->prepare("SELECT userEmail FROM users WHERE userEmail = ?");
            $res -> execute([$email]);
            $row = $res->fetch(PDO::FETCH_ASSOC);
            $count = $res->rowCount();

            if($count !== 0){
                $error = true;
                $emailError = "Provided Email is already in use.";
            }
        }
    // EMAIL VALIDATION

1 个答案:

答案 0 :(得分:2)

如果您只是想验证域部分,那么您可以扩展正则表达式以使用组:

if (preg_match('/^(.*)@(college1.edu|college2.edu|college3.edu)$/', $submitted_email)) {
    // Email is one of the three
}

如果每个大学的用户部分格式不同,则会遇到困难,如您的示例中我可以看到您正在检查电子邮件地址是否以字母“x”开头,然后是8个数字。你可能最好定义一个格式数组来检查和循环它们:

$formats = [
    '/^x\d{8}@student\.ncirl\.ie$/',
    '/^user.[a-z]+@some.other.college.edu$/',
    // and so on
];

$valid = false;

foreach ($formats as $format) {
    if (preg_match($format, $submitted_email)) {
        $valid = true;
        break;
    }
}

if ($valid) {
    // Do rest of registration logic
}
相关问题