Created
June 5, 2017 16:26
-
-
Save callumlocke/938b26b8b146b0c19d7169072caa9e83 to your computer and use it in GitHub Desktop.
Functions for validating and normalising postcodes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const postcodeRegex = /^[a-z]{1,2}\d[a-z\d]?\s*\d[a-z]{2}$/i; | |
const incodeRegex = /\d[a-z]{2}$/i; | |
const isValidPostcode = (p) => postcodeRegex.test(p.replace(/\s/g, '')); | |
const normalisePostcode = (p) => { | |
if (!isValidPostcode(p)) throw new Error('Invalid postcode'); | |
const spaceless = p.replace(/\s/g, ''); | |
const incode = spaceless.match(incodeRegex)[0].toUpperCase(); | |
const outcode = spaceless.replace(incodeRegex, '').toUpperCase(); | |
return `${outcode} ${incode}`; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment