JavaScript

Validate an integer string before converting it

For a complete integer field, validate the whole string and then check Number.isSafeInteger. ParseInt alone accepts a valid numeric prefix and can hide trailing invalid characters.

Worked example

Node.js example · save as example.mjs and run node example.mjs

function integerField(text) {
  if (!/^[+-]?\d+$/.test(text)) throw new Error("Expected an integer");
  const value = Number(text);
  if (!Number.isSafeInteger(value)) throw new Error("Outside safe range");
  return value;
}
console.log(integerField("42"));
try { integerField("42px"); } catch { console.log("rejected"); }

How it works

The anchors require the full input to match decimal integer syntax. Number then converts that validated string. The safe-integer check rejects values whose exact integer identity cannot be represented reliably by the Number type.

Limits and mistakes

This contract rejects whitespace, exponents, separators, and decimal points. That is deliberate; trim or support other formats only if the field requires them. Leading zeros remain allowed. Use BigInt for exact integers beyond the safe range.

Check the result

Expect 42 and rejected. Test an empty string, a negative value, and a value above Number.MAX_SAFE_INTEGER. Decide whether plus signs and leading zeros are acceptable.

Sources

Reference documentation for the behavior used in this guide: