首页 > 解决方案 > 使用不同的电子邮件类型注册

问题描述

我希望用户使用他们的学生电子邮件地址进行注册,我拥有的代码仅适用于一所大学,我希望拥有 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

标签: php

解决方案


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

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

如果每所大学的用户部分有不同的格式,就会出现困难,如在您的示例中,我可以看到您正在检查电子邮件地址是否以字母“x”开头,然后是八个数字。您最好定义一组要检查的格式,然后循环遍历它们:

$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
}

推荐阅读