sri-lanka-nic@sri-lanka/nic

Errors

All errors thrown by the library are instances of NICError, which extends the native Error class.

NICError

import { NICError } from "@sri-lanka/nic";
 
try {
  NIC.parse("invalid");
} catch (error) {
  error instanceof NICError; // true
  error instanceof Error; // true
  error.name; // "NICError"
  error.message; // "Invalid NIC structure"
}

Error Messages

MessageWhen it's thrown
Invalid NIC structureThe NIC doesn't match either 12-digit or 9-digit+letter pattern
Minimum age requirement not metThe person is younger than the minimum age (default: 15)
Maximum age requirement not metThe person is older than the maximum age
Invalid day of yearThe day-of-year value is out of range (not 1–365/366)
Invalid year for old format conversionTrying to convert a 20XX NIC to old format
Serial number too large for old formatThe serial number can't fit in old format (more than 3 digits)
NIC type is restricted by validation optionsonlyNew or onlyOld was set but the NIC is the wrong format

Catching Errors

The recommended pattern:

import { NIC, NICError } from "@sri-lanka/nic";
 
try {
  const result = NIC.parse(userInput);
  // use result
} catch (error) {
  if (error instanceof NICError) {
    // Show error.message to the user
    console.log(error.message);
  } else {
    // Unexpected error — re-throw
    throw error;
  }
}

With NIC.valid()

If you don't want to deal with try/catch, use NIC.valid():

if (NIC.valid(userInput)) {
  const result = NIC.parse(userInput);
  // safe to use
} else {
  // invalid NIC
}

Note: NIC.valid() catches NICError only. If your custom check function throws a TypeError or other non-NICError exception, it will still propagate.