If you have the whole postcode and only want to use the outcode, remove the last three characters and use what remains. All postcodes end with the pattern digit-alpha-alpha, so removing those characters will give the outcode; any string that does not fit that pattern or that does not give a valid outcode after removing that substring is not a valid postcode. (Source)
If you're willing to take on an external (and Internet-based) dependency, you could look at using something like https://postcodes.io, in particular the outcodes section of that API. I have no affiliation with postcodes.io; I just found it after a Google.
Per the documentation, /outcodes will return
- the outcode
- the eastings
- the northings
- the andministrative counties under the code
- the district/unitary authories under the code
- the administrative/electoral areas under the code
- the WGS84 logitude
- the WGS84 latitude
- the countries included in the code
- the parish/communities in the code
For reference, a call to /outcodes/TA1 returns:
{
"status": 200,
"result": {
"outcode": "TA1",
"longitude": -3.10297767924529,
"latitude": 51.0133987332761,
"northings": 124359,
"eastings": 322721,
"admin_district": [
"Taunton Deane"
],
"parish": [
"Taunton Deane, unparished area",
"Bishop's Hull",
"West Monkton",
"Trull",
"Comeytrowe"
],
"admin_county": [
"Somerset"
],
"admin_ward": [
"Taunton Halcon",
"Bishop's Hull",
"Taunton Lyngford",
"Taunton Eastgate",
"West Monkton",
"Taunton Manor and Wilton",
"Taunton Fairwater",
"Taunton Killams and Mountfield",
"Trull",
"Comeytrowe",
"Taunton Blackbrook and Holway"
],
"country": [
"England"
]
}
}
If you have the whole postcode, the /postcodes
endpoint will return considerably more detailed information which I will not include here, but it does include the outcode and the incode as separate fields.
I would, of course, recommend caching the results of any call to a remote API.