Validating UK Postcodes with Regex

In case anyone needs Regex for checking UK postcodes are valid.

This one will validate it’s the correct format (note this does not prove it’s an actual postcode - just that it is in the correct format). This has been tested in Bubble and works on the vast majority of postcodes (there are some weird ones out there that it doesn’t cover)

^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$

If you just want to check the outcode (the first bit of a postcode) use this
([A-Z]{1,2}[0-9]{1,2})([A-Z]{1,2})?(\W)?([0-9]{1,2}[A-Z]{2})?

Note- this one is uppercase only, use Bubble’s :uppercase to convert before your extract with regex

Hope it helps

Simon

2 Likes

@simon. Thanks for sharing this. From a general curiosity standpoint, is there a rationale for using Regex instead of an API call to a service like https://postcodes.io/?

GIR 0AA :slight_smile:

1 Like

Hey Dan,

For speed I guess, in my use case I am not actually shipping to it so don’t care about it being an actual postcode. I am using it to match against to see if service is provided in a given area. So this is quicker to implement and execute.

But I totally get that with lots of use cases postcode.io would make sense.

Simon

1 Like

This topic was automatically closed after 70 days. New replies are no longer allowed.