Validate the Whole Quantity String Before Converting It to a Number
A warehouse import can receive a quantity as text. If its contract requires a non-negative whole number, parsing a numeric prefix is too permissive: parseInt("12pcs", 10) returns 12 rather than rejecting the field. This example deliberately accepts only canonical ASCII decimal strings: "0", or a nonzero digit followed by digits. It rejects whitespace, leading zeros, signs, fractions and exponent…
Warehouses may receive product quantities as text strings, but simply parsing a numeric prefix can be too permissive. For instance, parseInt("12pcs", 10) returns the number 12 instead of rejecting the field. This example only accepts canonical ASCII decimal strings: "0" or a nonzero digit followed by digits, rejecting whitespace, leading zeros, signs, fractions, and exponent notation. These are application choices, not universal rules for every inventory system.
The code first checks if the input is a string and matches the required pattern using a regular expression. If not, it throws a TypeError. Then, it converts the string to a number. If the resulting number is not a safe integer, it throws a RangeError. Finally, it returns the quantity value.
Validating the quantity string before converting it to a number prevents issues with invalid input. For example, parseInt("12pcs", 10) returns 12, but the stricter quantity function throws a TypeError. The function also checks if the converted number is a safe integer, rejecting values outside the JavaScript Number safe integer range.
When implementing quantity validation, consider the business contract and adjust the tests accordingly. If leading zeros are allowed, explicitly state this in the contract and add corresponding tests. The provided code demonstrates a stricter approach, but it's not a live Shopify connector. In a Shopify 3PL import, the quantity still needs an agreed-upon unit and SKU mapping. Similarly, a drop shipping feed can be syntactically valid but refer to the wrong packing unit.
Keep validation errors attached to the source row instead of replacing them with zero. This ensures proper error tracking. The same boundary considerations apply to China fulfillment files sent to a China 3PL, even for a specification labeled "International Fulfillment for Folligen." Conversion success does not guarantee stock availability or permission to dispatch.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to