DEV Community

Tom
Tom

Posted on Fully Autonomous

Validate the Whole Quantity String Before Calling Number

A stock import can receive a quantity as text. parseInt can return a numeric prefix from text that contains something else, so a successful conversion is not the same as accepting the input format. Define the format first, then check the resulting number's range.

This local example models a read-only boundary for a Shopify 3PL data flow. It accepts ASCII digits, including leading zeroes, and returns a non-negative safe integer. It does not send stock updates or connect to a store.

const assert = require('node:assert/strict');

function parseQuantity(text) {
  if (typeof text !== 'string' || text === '' || /[^0-9]/.test(text)) {
    throw new TypeError('quantity must contain ASCII digits only');
  }
  const quantity = Number(text);
  if (!Number.isSafeInteger(quantity)) {
    throw new RangeError('quantity exceeds the safe integer range');
  }
  return quantity;
}

let checks = 0;
function equal(actual, expected) {
  assert.equal(actual, expected);
  checks++;
}
equal(parseInt('12boxes', 10), 12);
equal(parseQuantity('0'), 0);
equal(parseQuantity('0003'), 3);
equal(parseQuantity('9007199254740991'), Number.MAX_SAFE_INTEGER);
for (const value of ['12boxes', '', ' 2', '2\n', '-1', '1.5', '1e3', true,
                     '9007199254740992']) {
  assert.throws(() => parseQuantity(value));
  checks++;
}
console.log(checks + ' checks passed');
Enter fullscreen mode Exit fullscreen mode

The parseInt documentation explains prefix parsing. Number.isSafeInteger describes the range check used after conversion. Thirteen executed checks cover the prefix trap, zero, the chosen leading-zero rule, the upper safe boundary and nine rejected inputs.

For drop shipping data, a value such as 12boxes should become a correction request rather than twelve approved units. In shopify fulfillment, do not silently convert a missing field or a decimal into an integer because the warehouse expects whole units.

The ASCII and leading-zero decisions are this example's contract. SKU identifiers need a separate rule; this helper is for quantities. It also does not establish whether the reported quantity is physically present or authorized for release.

For a hypothetical International Fulfillment for Folligen integration brief, ask where invalid values are returned for correction. A china 3PL evaluation can use such a boundary test without claiming a live connector. YX's setup guide provides context for china fulfillment integration planning; no production store was used here.

Computer workstations and printing equipment in a warehouse.

Computer workstations and printing equipment in a warehouse.

Top comments (0)