How to Restrict Email Domains

Overview

Would you like to restrict certain email domains from your form? It may be necessary to block certain domains from your WPForms. In this tutorial, we’ll show you how to use a PHP snippet to create a whitelist of accepted domains so that all other domains will be blocked from submitting form entries on your site.

Setup

In order to create your whitelist, simply copy this code to your site.

/*
 * Whitelist email domains from your WPForms.
 *
 * @link https://wpforms.com/developers/how-to-restrict-email-domains/
 *
*/
function wpf_whitelist_domains( $field_id, $field_submit, $form_data ) {
    $domain          = substr( strrchr( $field_submit, "@" ), 1 );
    $whitelist       = array( 'icloud.com', 'me.com' );
    if( ! in_array( $domain, $whitelist ) ) { 
        wpforms()->process->errors[ $form_data['id'] ][ $field_id ] = esc_html__( 'Email domain not accepted!', 'wpforms' );
        return;
    }
}
add_action('wpforms_process_validate_email', 'wpf_whitelist_domains', 10, 3 );

Remember to update the array( 'icloud.com', 'me.com' ); to include the domains you want in your $whitelist.

With the PHP snippet added, you can now restrict certain email domains from your form.

And that’s all you need! You have now successfully restricted email domains from your form. Would you like to restrict the number of characters allowed in your text fields? Take a look at our tutorial on How to Limit the Number of Characters for a Text Field.

Filter Reference: wpforms_process_validate_email