Emmanuel Akinfulubi

JavaScriptBasic

Validate a required form field in JavaScript

Beginner · 3 min read

Almost every form has required fields, the ones marked with a star that you can't leave blank. Checking them sounds trivial: if (!value) show an error. That one line is wrong in three ways. It rejects real answers like 0 and false, and it accepts a field full of spaces.

In this tutorial you will write a function called isProvided that decides whether a field was really filled in. It rejects empty text, spaces only, null, undefined and failed number conversions, and accepts a seat count of 0 and a deliberate "no" (false). You need to know what if, strings and numbers are.

Truthy and falsy

When you write if (value), JavaScript turns value into true or false. Values that become false are called falsy. There are only a few of them, and the ones that matter here are:

Output

''  0  false  null  undefined  NaN

Everything else is truthy, including a string made of spaces.

JavaScript

console.log(Boolean(0));     // false
console.log(Boolean(false)); // false
console.log(Boolean('   ')); // true

That's the whole problem. "Falsy" and "empty" are different lists. 0 extra bags is an answer. Unticking "I want air conditioning" (false) is an answer. Three spaces is not.

Missing values: null and undefined

undefined usually means a value was never set, for example a field that wasn't on the form at all. null usually means "deliberately empty". Both mean nothing was given.

NaN ("not a number") is what you get when text can't be turned into a number: Number('abc') is NaN. It's a sign that the conversion failed, so it isn't an answer either.

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

116 A required field that is genuinely required

easy

Decide whether a form field was filled in. It must reject an empty string, spaces only, null and undefined — and accept a fare of 0 and an air-conditioning answer of false, both of which are real answers.

Stuck? Three hints, smallest first
  1. 1. if (value) throws away 0 and false along with the blanks.
  2. 2. A string needs trimming before it is measured.
  3. 3. NaN is what a failed Number() leaves behind, and it is not an answer.

Step 1: the one-liner and its three bugs

Step 1

const naive = (value) => Boolean(value);
console.log(naive(0));     // false, but 0 is a real answer
console.log(naive(false)); // false, but false is a real answer
console.log(naive('   ')); // true, but nothing was typed

We need to check each kind of value by its own rule.

Step 2: missing is missing

Step 2

function isProvided(value) {
  if (value === null || value === undefined) return false;
  return true;
}
console.log(isProvided(null));      // false
console.log(isProvided(undefined)); // false
console.log(isProvided(0));         // true
console.log(isProvided(false));     // true

=== checks for exactly null or exactly undefined, so 0 and false are no longer swept up with them. || means "or".

Step 3: text must have something in it after trimming

Step 3

function isProvided(value) {
  if (value === null || value === undefined) return false;
  if (typeof value === 'string') return value.trim().length > 0;
  return true;
}
console.log(isProvided('Yaba')); // true
console.log(isProvided('   ')); // false
console.log(isProvided(''));    // false

typeof value tells you what kind of value it is, as text: 'string', 'number', 'boolean' and so on. For strings, trim() removes spaces at both ends, and then the length must be more than 0.

Step 4: numbers must be real numbers

Step 4

function isProvided(value) {
  if (value === null || value === undefined) return false;
  if (typeof value === 'string') return value.trim().length > 0;
  if (typeof value === 'number') return Number.isFinite(value);
  return true;
}
console.log(isProvided(0));             // true
console.log(isProvided(Number('abc'))); // false

Oddly, typeof NaN is 'number', so NaN reaches this line. Number.isFinite returns true only for ordinary numbers. It is false for NaN and for Infinity, which you get from dividing by zero. Zero passes.

Step 5: check a whole form

Step 5

function isProvided(value) {
  if (value === null || value === undefined) return false;
  if (typeof value === 'string') return value.trim().length > 0;
  if (typeof value === 'number') return Number.isFinite(value);
  return true;
}
const form = { stop: 'Yaba', note: '   ', seats: 0, ac: false, fare: Number('abc') };
const missing = Object.keys(form).filter((k) => !isProvided(form[k]));
console.log(missing); // [ 'note', 'fare' ]

Object.keys(form) lists the field names, and filter keeps the ones that weren't provided. The note of spaces and the failed fare are flagged. The 0 seats and the false for air conditioning are accepted.

Step 6: the case this doesn't solve

Step 6

function isProvided(value) {
  if (value === null || value === undefined) return false;
  if (typeof value === 'string') return value.trim().length > 0;
  if (typeof value === 'number') return Number.isFinite(value);
  return true;
}
console.log(isProvided([])); // true

An empty array is a value, so it counts as provided. But if it came from a multi-select list, the person chose nothing. No single helper can know what "filled in" means for every field. A multi-select needs its own rule, such as value.length > 0.

The full solution

The answer panel has isProvided and the sample form. Its checks cover text, spaces only, an empty string, null and undefined, zero, false, NaN, the naive truthiness test getting all three wrong, and the empty array. Press Run to see the output.

The answer

function isProvided(value) {
  if (value === null || value === undefined) return false;
  if (typeof value === 'string') return value.trim().length > 0;
  if (typeof value === 'number') return Number.isFinite(value);
  return true;
}
const form = { stop: 'Yaba', note: '   ', seats: 0, ac: false, fare: Number('abc') };
console.log(Object.keys(form).filter((k) => !isProvided(form[k])), 'still to fill in');

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('text counts as provided', isProvided('Yaba'), true);
test('spaces only do not', isProvided('   '), false);
test('nor does an empty string', isProvided(''), false);
test('nor a missing value of either kind', [isProvided(null), isProvided(undefined)], [false, false]);
test('but zero is an answer', isProvided(0), true);
test('and so is a deliberate false', isProvided(false), true);
test('NaN is not, because it is a failed conversion', isProvided(Number('abc')), false);
test('a bare truthiness test disagrees on all three', [Boolean(0), Boolean(false), Boolean('   ')], [false, false, true]);
test('an empty array slips through, so a multi-select needs its own rule', isProvided([]), true);

if (!value) return 'required' is the bug this exercise exists to kill. It rejects 0, which is a valid number of extra bags; it rejects false, which is a customer deliberately declining air conditioning; and it accepts ' ', which is nothing at all. The falsy set and the empty set are different sets — exercise 98 makes the same point about || against ??.

So the check is per type: nullish is missing, a string is measured after trimming (exercise 104), a number must be finite so NaN from a failed Number() and Infinity from a division both fail, and anything else counts as given. The last assertion is deliberately uncomfortable: [] is a value, so this says provided, while a multi-select that submitted an empty array chose nothing. There is no universal answer to "is this filled in" — there is only the answer for this field, which is why the rule belongs next to the field rather than in one clever helper.

Common mistakes

  • Writing if (!value). It throws away 0 and false and lets ' ' through.
  • Not trimming text. A field of spaces looks filled in.
  • Forgetting NaN is a number. typeof NaN is 'number', so check with Number.isFinite.

Try it yourself

  1. Add a rule so an empty array returns false.
  2. Write missingFields(form, required) that only checks the field names listed in required.
  3. Return a message instead of a list: 'Please fill in: note, fare'.

Keep practising

Newsletter

New writing, when it lands.

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