Halloween Sale 15% off Ends in See the plans
PHP

Require a Work Email in Gravity Forms

Asks for a company email address instead of Gmail, Yahoo or other free webmail in Gravity Forms email fields, for B2B lead and demo request forms.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_gf_free_providers = array( 'gmail.com', 'googlemail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'live.com', 'aol.com', 'icloud.com', 'gmx.com', 'proton.me', 'protonmail.com', 'mail.com', 'yandex.com' );

add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) use ( $wpide_gf_free_providers ) {
    if ( 'email' !== $field->type || ! $result['is_valid'] ) {
        return $result;
    }

    $classed = false;
    foreach ( $form['fields'] as $f ) {
        if ( false !== strpos( ' ' . $f->cssClass . ' ', ' work-email ' ) ) {
            $classed = true;
            break;
        }
    }
    if ( $classed && false === strpos( ' ' . $field->cssClass . ' ', ' work-email ' ) ) {
        return $result;
    }

    $email  = strtolower( trim( is_array( $value ) ? (string) reset( $value ) : (string) $value ) );
    $domain = (string) substr( strrchr( $email, '@' ), 1 );

    if ( $domain && in_array( $domain, $wpide_gf_free_providers, true ) ) {
        $result['is_valid'] = false;
        $result['message']  = 'Please use your work email address.';
    }

    return $result;
}, 10, 4 );

Notes

Add the CSS class work-email to an email field in the form editor (Appearance tab) to check only that field; without the class every email field is checked.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.