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 restrict the email domains you don’t wish to accept on your forms.

Setup

In order to restrict the email domains, copy this code to your site.

/*
 * Block email domains from your WPForms.
 *
 * @link https://wpforms.com/developers/how-to-restrict-email-domains/
 *
*/
function wpf_restrict_domains( $field_id, $field_submit, $form_data ) {
	
	$domain          = substr( strrchr( $field_submit, "@" ), 1 );
	$restrict_list   = array( 'gmail.com', 'hotmail.com' );

	if( in_array( $domain, $restrict_list ) ) { 
		wpforms()->process->errors[ $form_data['id'] ][ $field_id ] = sprintf( esc_html__( 'Email domain not accepted!', 'wpforms' ) );
		return;
	}
}
add_action('wpforms_process_validate_email', 'wpf_restrict_domains', 10, 3 );

Remember to change the array( 'gmail.com', 'hotmail.com' ) to match the domains you wish to restrict and separate each domain name with a comma.

As the form is completed, it will check the email domain submitted and if the domain is found on the list above, a verification error will appear on the page to let the user know the email domain is not accepted.

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 these 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.