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; }
I tried that and I get this error
Your PHP code changes were rolled back due to an error on line 12 of file wp-content/themes/ohio-child/functions.php. Please fix and try saving again.
syntax error, unexpected ‘=’, expecting ‘)’
Apologies, my site updated and had ASCII instead of characters in the code block. It should be okay now. Anywhere where it said & lt; (no space between the & and lt) replace it with < and anywhere it said & gt; replace it with >
Hope that helps.
What actual rules is the regex here using to check the uk number is valid? I’ve read loads about how to check UK numbers and it’s very complex..
Essentially it’s just UK landlines, and you’re right, it’s a very complex way of validating things since there are now so many different permutations.
Thanks so much for this , wish gravity would add some functionality for UK numbers to validate.