Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@richardW8k
Last active March 31, 2016 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardW8k/8597284 to your computer and use it in GitHub Desktop.
Save richardW8k/8597284 to your computer and use it in GitHub Desktop.
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
Copy link

adijeff 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
Copy link

adijeff 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
Copy link

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