35 min·advanced

Lesson 3

Security & validation

Build a practical mental model for security & validation and use it in working JavaScript.

By the end, you will be able to…

  • Explain security & validation in your own words
  • Use security & validation in a small program
  • Recognize and debug a common failure mode

Build the mental model

Never trust input from users, forms, or external APIs — validate it explicitly before using it. On the web, also avoid injecting untrusted strings as HTML (XSS) and always validate on the server, since client-side checks can be bypassed entirely.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: Rejects negative numbers, decimals, and non-numeric strings

Why this matters

Nearly every real security incident traces back to trusting input that turned out to be malicious or malformed.

Real-world example

Every login form rate-limiting attempts and validating input server-side, even though it also validates client-side, follows this principle.

Common mistakes

  • Trusting client-side validation as the only line of defense
  • Rendering untrusted user input as HTML instead of as text
  • Not validating numeric ranges, allowing negative quantities or prices

Try it yourself

Challenge

Write sanitizeQuantity(input) that only accepts positive whole numbers, defaulting to 1 otherwise.

Practice

Knowledge check

Why is client-side-only validation insufficient for security?

Summary

Validate all external input explicitly, treat it as untrusted, and never rely on client-side checks alone.