BuddyPress: Allow only one email domain to register

Finally, I found the solution. Here is the code if anyone has the same issue and want to refer it.

Using Action

function wf_validate_email_domain()
{
    global $bp;

    $email          = $bp->signup->email;
    $email_exploded = explode('@', $email);
    // split on @ and return last value of array (the domain)
    $domain = array_pop($email_exploded);

    $email_domains = get_option('allowed_email_domains');

    $allowed_email_domains = array_map('trim', explode(',', $email_domains));

    if ( ! in_array($domain, $allowed_email_domains)) {
        $bp->signup->errors[ 'signup_email' ] = __('You cannot register using this email', 'workfront');
    }

}

add_action('bp_signup_validate', 'wf_validate_email_domain');

I also found a solution using the same filter as in my question. The answer provided by @Damocles and here is the original answer link. However, for convenience, I am pasting code here.

Using Filter

function wf_validate_email_domain($result)
{

    $email = $result[ 'user_email' ];

    // make sure we've got a valid email
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // split on @ and return last value of array (the domain)
        $domain = array_pop(explode('@', $email));

        $email_domains = get_option('allowed_email_domains');

        $allowed_email_domains = array_map('trim', explode(',', $email_domains));

        if ( ! in_array($domain, $allowed_email_domains)) {
            $result[ 'errors' ]->add('user_email', __('You cannot register using this email', 'workfront'));
        }

    }

    return $result;

}

add_filter('bp_core_validate_user_signup', 'wf_validate_email_domain');

Leave a Comment