|
| 1 | +/** |
| 2 | + * uk-postcode |
| 3 | + * Parse and validate UK postcodes |
| 4 | + * @author Lovell Fuller |
| 5 | + * |
| 6 | + * This code is distributed under the Apache License Version 2.0, the terms of |
| 7 | + * which may be found at http://www.apache.org/licenses/LICENSE-2.0.html |
| 8 | + */ |
| 9 | + |
| 10 | +/** |
| 11 | + * Postcode object |
| 12 | + */ |
| 13 | +class Postcode { |
| 14 | + outward: string | null; |
| 15 | + inward: string | null; |
| 16 | + |
| 17 | + constructor() { |
| 18 | + this.outward = null; |
| 19 | + this.inward = null; |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * Does this postcode have valid outward part? |
| 24 | + */ |
| 25 | + isValid(): boolean { |
| 26 | + return this.outward !== null; |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * Does this postcode have valid outward and inward parts? |
| 31 | + */ |
| 32 | + isComplete(): boolean { |
| 33 | + return this.outward !== null && this.inward !== null; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Does this postcode have a valid outward and no inward part? |
| 38 | + */ |
| 39 | + isPartial(): boolean { |
| 40 | + return this.outward !== null && this.inward === null; |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Format postcode with/without a space between the outward and inward portions |
| 45 | + */ |
| 46 | + toString(): string { |
| 47 | + let formatted = ""; |
| 48 | + if (this.isValid()) { |
| 49 | + formatted = this.outward as string; |
| 50 | + if (this.isComplete()) { |
| 51 | + formatted = formatted + " " + (this.inward as string); |
| 52 | + } |
| 53 | + } |
| 54 | + return formatted; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +/** Export factory method */ |
| 59 | +export function fromString(postcodeAsString: string): Postcode { |
| 60 | + let postcode = new Postcode(); |
| 61 | + if (typeof postcodeAsString === "string") { |
| 62 | + let clean = postcodeAsString.toUpperCase().replace(/[^A-Z0-9]/g, ""); |
| 63 | + if (clean.match(/^[A-Z]{1,2}[0-9R][0-9A-Z]?[0-9][ABD-HJLNP-UW-Z]{2}$/)) { |
| 64 | + postcode.outward = clean.substring(0, clean.length - 3); |
| 65 | + postcode.inward = clean.substring(clean.length - 3); |
| 66 | + } else if (clean.match(/^[A-Z]{1,2}[0-9][0-9A-Z]?$/)) { |
| 67 | + postcode.outward = clean; |
| 68 | + } |
| 69 | + } |
| 70 | + return postcode; |
| 71 | +} |
0 commit comments