Recently a client needed a function or two for Gravity Forms to process UK telephone numbers, and asked that they are between 7 and 15 characters in length. The following Gravity forms filters do exactly what’s needed.

Paste them in to your theme’s function.php and with a little modification you should be good to go.

UK Phone Number Format

Using a simple regex function, we can create a new mask for telephone fields that eliminates unnecessary characters for validation and return the default error if it’s incorrect, like so:

add_filter( 'gform_phone_formats', 'uk_phone_format' );
function uk_phone_format( $phone_formats ) {
    $phone_formats['uk'] = array(
        'label'       => 'UK Telephone Number',
        'mask'        => false,
        'regex'       => '/^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/',
        'instruction' => false,
    );
 
    return $phone_formats;
}

That function adds an additional option (UK Telephone Number) to the Phone Format box when editing the Gravity Form field as shown below.

Limit Between a Certain Number of digits

Not the most elegant of functions, but working well all the same, the function below sets a minimum and maximum number of characters for a Gravity Form field, and displays a different error message for each. The part of the function that says ‘gform_field_validation_1_5‘ indicates the location/ID of the field (Form 1, Input Field 5).

// Add Gravity Forms Min and Max Character Length

add_filter("gform_field_validation_1_5", "validate_chars_count", 10, 4);
    function validate_chars_count($result, $value, $form, $field){

if (strlen($value) < 7) { // Minimum number of allowed characters 
$result["is_valid"] = false; 
$result["message"] = "Please enter at least 7 numbers.";
        } 

if (strlen($value) > 15 ) { // Maximum number of allowed characters
    $result["is_valid"] = false;
    $result["message"] = "Please enter less than 15 numbers.";
      }  
    
return $result;
    }