Whitelist Specific Email Domain [RESOLVED]

Hello,
i`m trying to implement an Domain Whitelist Function for specific Forms. My Current code is:

add_filter( 'gform_field_validation_4','validate_email', 10, 4);   
function validate_email ( $result, $value, $form, $field ) {
	
	 $whitelisted_domain = array(
		 'domain1.com',
         'domain2.com'
	 );
	foreach ($whitelisted_domain as $term) {
	if ( $field->get_input_type() === 'email' && $result['is_valid'] && in_array(strpos($value, $term) ) ) {

		$result['is_valid'] = false;
		$result['message']  = 'E-Mailadresse not approved.';
		
	}
}
	return $result;
}

But i don´t getting this work. Can someone help me with this?
The E-Mail Adress should get checked based on a whitelist Domain list. If the Mailadresse doesn´t containt in the Whitelist domain, the User should get an notice.

Hi Stefan. I recommend enabling Gravity Forms logging and adding some custom logging statements to your code so you can see what is being executed, and what the values are, so you can figure out why it’s not working.

First, enable Gravity Forms logging:

Next, add some custom logging statements to your code:

I like to log inside every loop or conditional and any time you set a variable or retrieve a value. With the additional logging and Gravity Forms logging active, you can check the Gravity Forms Core log and see what is going on. If you need assistance with the log, please share the link to the log file and your updated code so we know what logging statements to look for. Thank you.

1 Like

The logic you’re checking here wouldn’t really work for what you’re trying to do.

You would first want to start with allowing all the standard validation in the plugin to do its checks prior to running anything custom, then flagging the submission as invalid until your custom check passes.

You’d then want to loop through each allowed domain you’ve declared and then change the validation result back to true if you find a partial match in an email field value.

Something like the following would roughly do the above. Remember that this and your original snippet would only run for form #4 as defined in the filter name on the first line.

add_filter( 'gform_field_validation_4','validate_email', 10, 4);
function validate_email ( $result, $value, $form, $field ) {

    $whitelisted_domain = array(
        'domain1.com',
        'domain2.com'
    );

    if ( $field->get_input_type() === 'email' && $result['is_valid'] ) {

        $result['is_valid'] = false;
        $result['message']  = 'E-Mailadresse not approved.';

        foreach ( $whitelisted_domain as $term ) {
            if ( strpos( $value, $term ) ) {
                $result['is_valid'] = true;
                break;
            }
        }
    }
    return $result;
}
1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.