Skip to content

Instantly share code, notes, and snippets.

@DanBeckett
Last active March 29, 2018 13:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanBeckett/596ddf100505a065980e to your computer and use it in GitHub Desktop.
Save DanBeckett/596ddf100505a065980e to your computer and use it in GitHub Desktop.
Validate Gravity Forms standard multi-part Address field to check for a UK Valid Postcode
add_filter("gform_field_validation_[FORM_ID]_[FIELD_ID]", "uk_postcode_validation", 10, 4);
function uk_postcode_validation($result, $value, $form, $field){
//address field will pass $value as an array with each of the elements as an item within the array, the key is the field id
$postcode = $value["[FIELD_ID].5"];
//the default regex is valid both with and without the space in the middle.
//to force the space, replace with the following:
//'#^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})$#'
if(!(preg_match('#^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$#', $postcode))) {
$result["is_valid"] = false;
$result["message"] = "Please enter a valid postcode (including the space).";
}
return $result;
}
@DanBeckett
Copy link
Author

You can also use this on a flat text field to do the same job, if you replace line 6 with

    $postcode = $value;

@egreenman
Copy link

I'm not too sure if this is allowed so please excuse me if i'm commenting out of place!

Can someone please talk me through this dummy style. I really need this functionality on my gravity forms but I have no idea what the different parts mean and where to put this code. Ideally, I just want postcodes in the BA and BS areas.

Thank you,

Elliott

@LiamWinterton
Copy link

LiamWinterton commented Mar 29, 2018

Hi dude,

Using this, and the validation is great, but doesn't seem to show any errors when a postcode isn't valid?

EDIT: Nevermind. Don't just copy and paste folks, we should know better by now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment