Credit Card Expiry Validation With Clock Injection

Parse MM/YY card expiry values, compare them against an injectable clock and report whether the card is valid through month end.

JavascriptForm Validation

Code

javascriptsnippet
26 lines
export function parseExpiry(value) {
  if (typeof value !== "string") throw new TypeError("expiry must be a string");
  const match = /^(0[1-9]|1[0-2])\s*\/\s*(\d{2})$/.exec(value.trim());
  if (!match) throw new RangeError("expiry must use MM/YY format");
  const month = Number(match[1]);
  const year = 2000 + Number(match[2]);
  return { month, year };
}

export function isExpired(value, now = new Date()) {
  const { month, year } = parseExpiry(value);
  if (Number.isNaN(now.getTime())) throw new TypeError("now must be a valid Date");
  const endOfMonth = new Date(Date.UTC(year, month, 1));
  return now.getTime() >= endOfMonth.getTime();
}

export function validateExpiry(value, now = new Date()) {
  const parsed = parseExpiry(value);
  const expired = isExpired(value, now);
  return {
    valid: !expired,
    reason: expired ? "expired" : null,
    month: parsed.month,
    year: parsed.year,
  };
}

How it works

Credit Card Expiry Validation With Clock Injection is built around the functions parseExpiry, isExpired and validateExpiry.

TypeError and RangeError is the guard’s signal — thrown at the branch, before any partial work happens.

The result comes back as an object carrying month.

Points of care

  • The guard typeof value !== "string" short-circuits the flow with an early throw when its condition holds.

Applying it

The main signature reads export function parseExpiry(value)

The surface worth importing is parseExpiry; the helpers around it are private to the snippet.

The call returns month.

Statements that matter

if (Number.isNaN(now.getTime())) throw new TypeError("now must be a valid Date");
if (typeof value !== "string") throw new TypeError("expiry must be a string");
const match = /^(0[1-9]|1[0-2])\s*\/\s*(\d{2})$/.exec(value.trim());

Interactive Tools for This Topic

FAQ

Does `parseExpiry` modify its input?
No mutation happens — the function reads its input and returns a new value.
What happens on invalid input?
The code refuses to continue: `TypeError` and `RangeError` is thrown while the state is still recoverable.
Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `parseExpiry`, `isExpired`, `validateExpiry` at load time.