I’m using a single line text field in Gravity forms with an input mask and need a custom mask for a UK postcode. Does anyone have a working example of a UK postcode input mask? Thanks
Hi there,
You can use this custom input mask for basic formatting guidance:
**** 9aa
This accepts up to 4 alphanumeric characters, a space, then one digit and two letters (like SW1A 1AA). Keep in mind this won’t cover every UK postcode format perfectly since they vary quite a bit.
For the most reliable solution, I suggest adding custom validation using regex. This ensures the postcode matches proper UK formatting before the form submits.
Add this code to your child theme’s functions.php file:
add_filter( 'gform_field_validation_X_Y', 'validate_uk_postcode', 10, 4 );
function validate_uk_postcode( $result, $value, $form, $field ) {
if ( $result['is_valid'] ) {
// UK postcode pattern
$pattern = '/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s?(\d[A-Z]{2})$/i';
$clean_value = trim( preg_replace( '/\s+/', ' ', $value ) );
// Validate format
if ( ! preg_match( $pattern, $clean_value ) ) {
$result['is_valid'] = false;
$result['message'] = 'Please enter a valid UK postcode (e.g., SW1A 1AA).';
}
}
return $result;
}
Important: Replace X_Y with your actual form ID and field ID. For example, if your form is ID 5 and the postcode field is ID 3, use gform_field_validation_5_3.
This regex pattern validates proper UK postcode structure and works with or without spaces. It runs when the form submits and displays an error message if the format is incorrect.
Give it a try, and let me know how that goes! ![]()
That’s great, thank you, I’ll give it a try ![]()
You’re welcome, Emma.
If you’re having difficulties, you can follow this step-by-step video tutorial to implement custom UK postal code validation on your site: ![]()
Let me know if you still need any help!
Hi @emma.bumstead,
I’ve built a plugin that automatically validates postal codes to ensure only 100% valid codes are submitted. Currently, users can bypass the regex pattern and enter fake or invalid postal codes.
However, I’ve integrated a third-party API for validation, so it’s no longer possible to submit an invalid postal code, as shown in the screen recording below.
If you’d like to use this on your website, I’d be happy to provide you with the plugin. Please let me know. Thank you!
Screen recording: ![]()
