Skip to content

parsePort

Parses a value into a valid TCP/UDP port number. This parser combines the normalizePort semantic normalizer with the validatePort validator to produce a canonical port value.

The parser never throws and never mutates input. It returns a structured ParseResult<number> describing success or failure.

Signature

function parsePort(
    value: unknown,
    field?: string,
    options?: { strict?: boolean }
): ParseResult<number>

Behavior

  • Accepted inputs (non-strict mode):
  • Integers from 0 to 65535.
  • String representations of those integers (whitespace allowed).
  • Accepted Inputs (Strict Mode):
  • Integers from 1 to 65535
  • Digit-only strings with:
    • no whitespace
    • no leading zeros
    • no signs (+ or -)
  • Rejected Inputs (Normalization Error):
  • Out-of-range numbers (65536, -1).
  • Non-integer numbers (3.14).
  • Malformed numeric strings ("80.5", "08", in strict mode).
  • These produce: "Value could not be normalized into a valid port number".
  • Rejected Inputs (Validation Error):
  • Non-numeric strings ("abc").
  • Empty or whitespace-only strings.
  • Objects, arrays, functions.
  • Booleans.
  • null and undefined.
  • These produce: "Value must be a valid port number (0–65535)".

Returns

  • ok: true: And the port number when parsing succeeds.
  • ok: false, value: null: And a list of issues when parsing fails.

Examples

parsePort("8080")
// { ok: true, value: 8080, issues: [] }

parsePort("080", "port", { strict: true })
// { ok: false, value: null, issues: ["Value could not be normalized into a valid port number"] }

parsePort("abc")
// { ok: false, value: null, issues: ["Value must be a valid port number (0–65535)"] }

Notes

  • Strict mode is useful for configuration files and security-sensitive contexts.
  • Non-strict mode is more forgiving for user input.