Skip to content

parse

parse(input, options?): ParseResult

Reads a postcode that a user typed or pasted. It accepts spaces, hyphens, dashes and any letter case. It never throws for a string. Input over the input limit of the spec fails with bad_length before parse normalises it, so long text cannot stall a server.

After normalisation, parse applies these checks in order. The first check that fails sets error.code:

  • empty: no character remains.
  • legacy_code: exactly 6 ASCII digits remain. These are old NIPOST postcodes.
  • bad_character: a character other than A to Z and 0 to 9 remains.
  • bad_length: the length is not 11. With allowPartial, the lengths 2, 4, 7 and 9 also pass.
  • unknown_state: the first two characters are not a state code.
  • bad_segment: a segment breaks its rule, such as an LGA of 00.

For unknown_state and bad_segment, error.segment names the failing segment. Both codes can also set error.suggestion to the canonical form of one fixed code. The fix replaces a look-alike character that is in the wrong place, such as the letter O in an LGA. It never changes the district. The suggestion is null when no fix applies, or when the fixed code does not parse. A suggestion is a hint only. parse never returns a fixed code as a success.

string

Text from a user.

Readonly<{ allowPartial?: boolean; }> = {}

Set allowPartial to accept a code that stops after a segment.

ParseResult

The postcode, or the reason that the input is not one.

const parsed = parse('ek 01 a03 fk 01');
if (parsed.ok) {
parsed.value.canonical; // 'EK-01-A03-FK-01'
}
const mistyped = parse('ek o1 a03 fk 01'); // a letter o where a zero belongs
if (!mistyped.ok) {
mistyped.error.code; // 'bad_segment'
mistyped.error.segment; // 'lga'
mistyped.error.suggestion; // 'EK-01-A03-FK-01'
}

Unofficial. Not made or endorsed by NIPOST.