Halloween Sale 15% off Ends in See the plans
PHP

Stricter Phone Validation in Gravity Forms

Checks Gravity Forms phone fields set to the international format for a realistic number of digits and only valid characters, instead of accepting any text.

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

Code

$wpide_gf_phone_min = 7;
$wpide_gf_phone_max = 15;

add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) use ( $wpide_gf_phone_min, $wpide_gf_phone_max ) {
    if ( 'phone' !== $field->type || ! $result['is_valid'] || ( ! empty( $field->phoneFormat ) && 'standard' === $field->phoneFormat ) ) {
        return $result;
    }

    $phone = trim( (string) $value );
    if ( '' === $phone ) {
        return $result;
    }

    $digits = strlen( preg_replace( '/\D/', '', $phone ) );

    if ( ! preg_match( '/^\+?[0-9\s().\-]+$/', $phone ) || $digits < $wpide_gf_phone_min || $digits > $wpide_gf_phone_max ) {
        $result['is_valid'] = false;
        $result['message']  = 'Please enter a valid phone number, including the country code.';
    }

    return $result;
}, 10, 4 );

Notes

Fields using the US (###) ###-#### format keep Gravity Forms' own check; adjust the digit range for your country.

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.