Drill

ProblemsJavaScript › validation

Read a quantity someone typed

easyvalidationJavaScript

A stock adjustment screen takes a quantity as free text, and the parser refuses anything it cannot trust.

validQuantity(text: string) → int

Solve it in the editor →

Where you start

function validQuantity(text) {
  
}

Worked examples

CallResult
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 JavaScript
function validQuantity(text) {
  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;
}

The same problem in another language

More validation problems in JavaScript