Validate Decimal ID Strings at a JavaScript API Boundary
Learn how to strictly validate incoming decimal identifier strings in JavaScript APIs while preserving precision and avoiding common JSON parsing pitfalls.
Table of Contents1 sections

When an API receives an identifier, treating it as a raw number often leads to precision loss or unexpected formatting issues. To maintain data integrity, you must enforce a strict validation policy on incoming decimal strings before your application logic processes them.
Quick solution:
const isValidDecimalId = (str) => typeof str === 'string' && /^\d{1,20}$/.test(str);
// Usage: if (!isValidDecimalId(input.id)) throw new Error('Invalid ID');
Understanding the API Boundary
When you receive data from a client, the transport format is typically JSON. According to the MDN documentation on JSON.parse, the parser converts numeric tokens into standard JavaScript numbers. This process is dangerous for identifiers that exceed the safe integer limit, as the engine may truncate or round the value. By enforcing a string-only policy for identifiers at the boundary, you ensure that the raw sequence of digits remains untouched by the parser’s numeric conversion logic. This boundary is the first line of defense against malformed data that could otherwise corrupt your database or cause silent logic errors in your application. Relying on the parser to handle large numbers is a common architectural mistake that ignores the inherent limitations of floating-point representation in the JavaScript runtime.
Defining the Validation Policy
A robust validation policy treats identifiers as opaque text rather than mathematical values. This distinction is critical because identifiers often contain leading zeros or exceed the 53-bit precision limit of standard JavaScript numbers. If you need to handle large numeric values safely, you might also need to serialize BigInt JSON without losing precision when sending data back to the client. For inbound validation, your schema should explicitly reject signs, exponents, and non-digit characters to prevent injection or malformed data from reaching your database. By treating these identifiers as strings, you maintain the exact representation provided by the client, which is essential for systems that rely on specific formatting or length constraints. This approach ensures that your application remains decoupled from the limitations of the JSON specification, allowing you to handle arbitrary-precision integers without relying on the engine’s internal number representation.
Common Failure Modes and Misuse
Developers often make the mistake of allowing loose type checking, such as using Number() or parseInt() on an identifier string. This approach is flawed because it silently converts valid identifiers into incorrect numeric representations. Another common error is failing to check for leading zeros. If your system treats “00123” and “123” as distinct entities, a numeric cast will collapse them into the same value, causing collisions. Always validate the string length and character set before attempting any transformation. Furthermore, failing to check the input type can lead to prototype pollution or unexpected behavior if an attacker sends an object or array instead of a string, which the regex test might handle inconsistently depending on the environment. You must also guard against Unicode digits that might bypass simple regex checks if the environment or locale settings interpret them as numeric characters.
| Scenario | Input | Policy Result | Reason |
|---|---|---|---|
| Standard ID | “9007199254740993” | Accept | Within length limit, digits only |
| Leading Zeros | “00123” | Accept | Preserves meaningful identifier format |
| Numeric Token | 9007199254740993 | Reject | Must be a string to prevent precision loss |
| Scientific Notation | “1e5” | Reject | Contains non-digit characters |
| Overlong ID | “123456789012345678901” | Reject | Exceeds 20-digit limit |
Handling BigInt Serialization Constraints
JavaScript does not natively support BigInt in JSON serialization, which is why MDN notes on BigInt and JSON serialization emphasize that BigInt values are not serializable by default. When your API boundary receives a string, you should keep it as a string throughout the validation phase. Only convert the string to a BigInt if you must perform arithmetic operations. If you convert too early, you risk throwing errors during serialization or losing the original formatting required by downstream systems. This strategy prevents the common pitfall of attempting to pass a BigInt object directly into a JSON stringifier, which will throw a TypeError. By keeping the identifier as a string until the final moment of processing, you maintain full control over the data lifecycle and avoid the pitfalls of implicit type coercion that often plague large-scale JavaScript applications.
Testing and Verification Strategies
To ensure your API boundary is secure and reliable, perform the following checks during your integration testing. First, verify that the validator rejects any input containing non-digit characters, including signs and decimal points. Second, confirm that identifiers with leading zeros are preserved as strings and not truncated by the parser. Third, test the maximum length constraint to prevent memory exhaustion or database overflow attacks. Fourth, ensure that numeric JSON tokens are rejected by the schema, forcing the client to send identifiers as quoted strings. Finally, validate that the application logic treats the identifier as a string throughout the entire request lifecycle. By automating these tests, you can catch regressions in your validation logic before they reach production, ensuring that your identifier handling remains consistent and secure across all API endpoints. These tests should be part of your CI/CD pipeline to prevent accidental changes to the validation schema that could introduce breaking changes for downstream consumers.
You Might Also Like
View all articles
Decode Split UTF-8 Chunks with TextDecoder Streaming
Learn how to correctly decode split UTF-8 chunks using JavaScript TextDecoder streaming options, handling byte boundaries and malformed input safely.

Promise allSettled Independent Task Failures
Learn how to handle independent JavaScript task failures safely using Promise.allSettled without losing partial outcomes.

Read repeated query parameters URLSearchParams getAll
Learn how to read repeated query parameters safely without losing data by using the URLSearchParams getAll method in JavaScript.