Problems › TypeScript › validation
Read a quantity someone typed
A stock adjustment screen takes a quantity as free text, and the parser refuses anything it cannot trust.
- Whitespace around the number is fine and is ignored.
- Only digits are allowed — no sign, no decimal point, no spaces inside.
- The value must be between 1 and 999.
- Anything else gives -1.
validQuantity(text: string) → int
Where you start
function validQuantity(text: string): number {
}
Worked examples
| Call | Result |
|---|---|
validQuantity("5") | 5 |
validQuantity(" 12 ") | 12 |
validQuantity("999") | 999 |
validQuantity("0") | -1 |
Hint
Trim, reject an empty result, then check every remaining character before you convert.
Reference solution in TypeScript
function validQuantity(text: string): number {
const t = text.trim();
if (t.length === 0) return -1;
for (const c of t) if (c < '0' || c > '9') return -1;
const n = Number(t);
return n >= 1 && n <= 999 ? n : -1;
}