'Limit Domain Registration on WooCommerce

How to limit access to specific domains on WooCommerce registration for user email?

I found this snippet of code that can do that, but it doesn't work on the WooCommerce Registration form for some reason.

It works if I go to the WP-login page though.

Any help is appreciated.

function is_valid_email_domain($login, $email, $errors ){

    $valid_email_domains = array("gmail.com", "yahoo.com");// allowed domains
    $valid = false; // sets default validation to false
    foreach( $valid_email_domains as $d ){
        $d_length = strlen( $d );
        $current_email_domain = strtolower( substr( $email, -($d_length), $d_length));
        if( $current_email_domain == strtolower($d) ){
            $valid = true;
            break;
        }
    }
 // Return error message for invalid domains
    if( $valid === false ){
        $errors->add('domain_whitelist_error',__( '<strong>ERROR</strong>: Registration is only allowed from selected approved domains. If you think you are seeing this in error, please contact the system administrator.' ));
    }
}

add_action('register_post', 'is_valid_email_domain',10,3 ); //this works
// add_action('woocommerce_register_form', 'is_valid_email_domain',10,0); //getting errors
// add_action('user_register', 'is_valid_email_domain',10,3 ); //getting errors


Solution 1:[1]

The correct hook to be used in WooCommerce is woocommerce_register_post action hook. Try this instead:

add_action('woocommerce_register_post','is_valid_registration_email_domain', 10, 3 );
function is_valid_registration_email_domain( $username, $email, $validation_errors ){
    $valid_email_domains = array( 'gmail.com', 'yahoo.com' ); // Allowed domains
    $valid = false; // sets default validation to false
    foreach( $valid_email_domains as $d ){
        $d_length = strlen( $d );
        $current_email_domain = strtolower( substr( $email, -($d_length), $d_length));
        if( $current_email_domain == strtolower($d) ){
            $valid = true;
            break;
        }
    }

    // Return error message for invalid domains
    if( ! $valid ){
        $error_text = __( "<strong>ERROR</strong>: Registration is only allowed from selected approved domains. If you think you are seeing this in error, please contact the system administrator.", "woocommerce" );
        $validation_errors->add( 'domain_whitelist_error', $error_text );
    }
}

Code goes in function.php file of your active child theme (or theme).

Tested and works.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LoicTheAztec