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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.