Skip to content

Instantly share code, notes, and snippets.

@callumlocke
Created June 5, 2017 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callumlocke/938b26b8b146b0c19d7169072caa9e83 to your computer and use it in GitHub Desktop.
Save callumlocke/938b26b8b146b0c19d7169072caa9e83 to your computer and use it in GitHub Desktop.
Functions for validating and normalising postcodes
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