0Pricing
JavaScript Academy · Lesson

Input validation, escaping basics

Validate and normalize inputs with small allowlists and guards; escape risky characters before showing text.

Big picture

Goal: Make inputs boring and safe.

  • Use guard clauses to reject early
  • Prefer allowlists over vague rules
  • Normalize to a simple shape
  • Escape special chars before showing text
Input validation, escaping basics — illustration 1

Number guard basics

Add simple guards: type check, range check, and normalize to a final value.

// Validate age: number and range guard
function parseAge(input) {
  // trim and parse
  const n = Number(input);
  if (!Number.isFinite(n)) return null; // reject non-numbers
  if (n < 0 || n > 130) return null;    // reject out-of-range
  return Math.floor(n);                  // normalize to integer
}

console.log("age ok:", parseAge("21"));
console.log("age bad:", parseAge("twenty"));
Input validation, escaping basics — illustration 2

All lessons in this course

  1. Input validation, escaping basics
  2. Safe object merging; freezing & sealing
  3. Error boundaries (conceptual) without frameworks
← Back to JavaScript Academy