Emmanuel Akinfulubi

JavaScriptBasic

Validate a number from a form input in JavaScript

Intermediate · 3 min read

Everything a person types into a web form arrives as text, even in a box meant for numbers. A seat count of 14 reaches your code as the string '14'. Before you can use it, you have to turn it into a number, and decide what to do when what they typed isn't a sensible number at all.

In this tutorial you will write a function called parseSeats that accepts 1 to 20 seats and, when it says no, gives a specific reason: nothing typed, not a number, not a whole number, or out of range. You need to know what strings, numbers, if and objects are.

Two ways to turn text into a number

Number(text) reads the whole text. If any part of it isn't a number, you get NaN, which means "not a number":

JavaScript

console.log(Number('14'));   // 14
console.log(Number('12kg')); // NaN

parseInt(text, 10) reads digits from the start and stops at the first thing it doesn't understand, quietly throwing the rest away. The 10 means "in base 10", ordinary decimal.

JavaScript

console.log(parseInt('12kg', 10)); // 12

For checking what a user typed, Number is the safer choice. If someone typed 12kg, you want to tell them, not guess.

The surprise: empty text is zero

JavaScript

console.log(Number(''));  // 0
console.log(Number(' ')); // 0

An empty box and a box with one space both turn into 0. If you convert first and check later, an empty quantity field looks like someone ordered zero seats. This is why the order of the checks matters.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

118 A number in range, out of a form field

fair

A seat count arrives from a form as text. Accept 1 to 20, and give a specific reason for each rejection: nothing typed, not a number, not a whole number, out of range. Also exercise 55, which clamped a number into a range; here an out-of-range value is a rejection rather than something to bend.

Stuck? Three hints, smallest first
  1. 1. Number('') is 0, so check for empty before converting.
  2. 2. Number('12kg') is NaN where parseInt('12kg') is 12.
  3. 3. Return the reason, not just false, or the form cannot tell the user anything useful.

Step 1: return a result object

A function that only returns true or false can't tell the form why something was wrong. So parseSeats returns an object: { ok: true, value } when the input is good, or { ok: false, reason } when it isn't.

Step 1

function parseSeats(raw) {
  const text = String(raw).trim();
  if (text === '') return { ok: false, reason: 'required' };
  return { ok: true, value: Number(text) };
}
console.log(parseSeats(''));    // { ok: false, reason: 'required' }
console.log(parseSeats(' 7 ')); // { ok: true, value: 7 }

trim() removes spaces at both ends, so a box of spaces is caught by the empty check. The empty check comes before any converting, so Number('') never gets the chance to turn it into 0.

Step 2: reject text that isn't a number

Step 2

function parseSeats(raw) {
  const text = String(raw).trim();
  if (text === '') return { ok: false, reason: 'required' };
  const n = Number(text);
  if (!Number.isFinite(n)) return { ok: false, reason: 'not a number' };
  return { ok: true, value: n };
}
console.log(parseSeats('12kg')); // { ok: false, reason: 'not a number' }

Number.isFinite(n) is true only for ordinary numbers, so it rejects NaN and Infinity. There is also an older global isFinite, but it converts its argument first, which brings back the same surprises you're trying to avoid.

Step 3: no fractions of a seat

Step 3

console.log(Number.isInteger(2));   // true
console.log(Number.isInteger(2.5)); // false

Number.isInteger checks for a whole number. Add it as the next check, with the reason 'not whole'.

Step 4: the range

Step 4

function parseSeats(raw, min = 1, max = 20) {
  const text = String(raw).trim();
  if (text === '') return { ok: false, reason: 'required' };
  const n = Number(text);
  if (!Number.isFinite(n)) return { ok: false, reason: 'not a number' };
  if (!Number.isInteger(n)) return { ok: false, reason: 'not whole' };
  if (n < min || n > max) return { ok: false, reason: 'out of range' };
  return { ok: true, value: n };
}
console.log(parseSeats('14'));  // { ok: true, value: 14 }
console.log(parseSeats('2.5')); // { ok: false, reason: 'not whole' }
console.log(parseSeats('99'));  // { ok: false, reason: 'out of range' }

min and max have default values, so the same function can check other ranges. Notice that an out-of-range value is rejected, not bent to fit. If someone types 99 seats, quietly changing it to 20 would book something they didn't ask for.

Each check returns as soon as it fails. That keeps the function flat and easy to read, with the most basic problem reported first.

Step 5: one more surprise

Step 5

function parseSeats(raw, min = 1, max = 20) {
  const text = String(raw).trim();
  if (text === '') return { ok: false, reason: 'required' };
  const n = Number(text);
  if (!Number.isFinite(n)) return { ok: false, reason: 'not a number' };
  if (!Number.isInteger(n)) return { ok: false, reason: 'not whole' };
  if (n < min || n > max) return { ok: false, reason: 'out of range' };
  return { ok: true, value: n };
}
console.log(Number('1e2'));        // 100
console.log(parseSeats('1e2'));    // { ok: false, reason: 'out of range' }
console.log(parseInt('1e2', 10));  // 1

1e2 is scientific notation for 1 × 10², which is 100. Number understands it; parseInt stops at the e and gives 1. With Number, at least the value is the one the text describes, and the range check catches it.

The full solution

The answer panel has the finished parseSeats and prints its result for seven inputs. The checks cover a good value, spaces around it, an empty field, Number('') and Number(' ') being zero, a unit stuck on the end, parseInt accepting it, a fraction and an out-of-range number. Press Run to see the output.

The answer

function parseSeats(raw, min = 1, max = 20) {
  const text = String(raw).trim();
  if (text === '') return { ok: false, reason: 'required' };
  const n = Number(text);
  if (!Number.isFinite(n)) return { ok: false, reason: 'not a number' };
  if (!Number.isInteger(n)) return { ok: false, reason: 'not whole' };
  if (n < min || n > max) return { ok: false, reason: 'out of range' };
  return { ok: true, value: n };
}
for (const raw of ['14', ' 7 ', '', '12kg', '2.5', '99', '1e2']) {
  console.log(JSON.stringify(raw).padEnd(8), JSON.stringify(parseSeats(raw)));
}

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a good value comes back converted', parseSeats('14'), { ok: true, value: 14 });
test('surrounding spaces are fine', parseSeats(' 7 ').value, 7);
test('an empty field is required, not zero', parseSeats('').reason, 'required');
test('which matters because Number of empty text is zero', Number(''), 0);
test('and whitespace converts to zero too', Number(' '), 0);
test('a unit stuck on the end is not a number', parseSeats('12kg').reason, 'not a number');
test('though parseInt would have accepted the first digits', parseInt('12kg', 10), 12);
test('a fraction of a seat is refused', parseSeats('2.5').reason, 'not whole');
test('and a valid number outside the range says so', parseSeats('99').reason, 'out of range');

Number('') being 0 is the trap that costs money. An empty quantity field converts to zero, zero passes a "must be a number" check, and the order is placed for nothing — or, with a range of 0 to 20, accepted outright. Test for empty text before converting, which is also why trim comes first: Number(' ') is 0 as well.

Number against parseInt is the other decision. parseInt reads as far as it understands and discards the rest, so '12kg' is 12 and '1e2' is 1; Number demands the whole string be numeric, so '12kg' is NaN and '1e2' is 100. For validating user input, whole-string strictness is what you want — silent truncation turns a typo into a plausible order. Number.isFinite rather than the global isFinite avoids the same coercion coming back in through the check itself, and returning a reason instead of a boolean is what lets the form point at the field and say why.

Common mistakes

  • Converting before checking for empty. Number('') is 0, so an empty box passes as zero.
  • Using parseInt on user input. '12kg' silently becomes 12. Use Number and reject NaN.
  • Returning only false. The form can't tell the user what to fix. Return a reason.

Try it yourself

  1. Turn each reason into a friendly message, like 'Please enter between 1 and 20 seats.'.
  2. Write parsePrice(raw) that allows up to two decimal places, so '1500.50' is fine but '1500.505' isn't.
  3. Call parseSeats('0x10'). What does Number('0x10') give, and should a seat count accept it?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.