Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
add to theme functions.php file to add uk as an available format on the phone type field and validation of uk style numbers, pattern from: http://www.coffeecup.com/help/articles/regular-expression-examples/#phonenumber-uk
<?php
//checks to see if a string is a valid UK phone number
add_filter( 'gform_field_validation', 'validate_phone', 10, 4 );
function validate_phone( $result, $value, $form, $field ) {
$pattern = "/^(((\+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}))?$/";
if ( $field->type == 'phone' && $this->phoneFormat != 'standard' && ! preg_match( $pattern, $value ) ) {
$result['is_valid'] = false;
$result['message'] = 'Please enter a valid phone number';
}
return $result;
}
@adijeff

This comment has been minimized.

Copy link

commented Feb 6, 2014

Hi Richard,

Thanks so much for this snippet. It is excellent except in one minor detail - the field is invalid even if left empty. I would like the field to be valid if empty (ie not a required field). Is that possible? Thanks.

@adijeff

This comment has been minimized.

Copy link

commented Feb 26, 2014

Just following up on this, if you add ^\s*$| to the pattern after the "/ then the field can be empty, or contain any amount of white space.

@mikakaltoft

This comment has been minimized.

Copy link

commented Mar 31, 2016

Hi, just tested this on my clients install, however, whenever I choose UK and click save, it jumps to this option "(###)###-####".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.