Computer Programming 1 (JavaScript) • Strings & Text Processing

Input Validation — I can validate user input (digits, ranges, allowed choices) and handle invalid cases gracefully.

Learn to protect your programs from bad data by checking every piece of user input before you use it.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

Every program that accepts user input faces a fundamental problem: people make mistakes, and sometimes they even enter data that is intentionally wrong. Since the earliest days of computing, programmers have dealt with input validation — the process of checking that data meets certain requirements before the program actually uses it. Without validation, a calculator app might crash when someone types a letter instead of a number, or a login form might allow a hacker to inject malicious code into a database.

The need for input validation grew as computers evolved from isolated machines operated by trained scientists into everyday tools used by millions of people. In early computing, the operator and the programmer were often the same person, so "bad input" was rare. As software moved to the web and mobile devices, programs had to handle input from anyone, anywhere, at any time. This shift made validation not just a nice feature, but a critical requirement for security and reliability.

1960s • Mainframe Era — Trusted Operators

Early programs assumed correct input because trained technicians ran them. Errors often crashed the entire system, requiring manual restarts.

1980s • Personal Computers — New Users, New Problems

With millions of non-technical users, software needed friendly error messages and checks to prevent unexpected crashes from typos and incorrect formats.

1995 • JavaScript Is Born — Client-Side Validation

Brendan Eich created JavaScript at Netscape, enabling web forms to check user input instantly in the browser before sending data to a server.

2000s • SQL Injection Attacks — Validation Becomes Security

High-profile database breaches showed that failing to validate input could allow attackers to steal or destroy data, making validation a cornerstone of web security.

2020s • Modern Frameworks & Built-In Validation

Libraries like React and Angular include powerful validation tools, but understanding the fundamentals remains essential for every developer.

The core question this lesson addresses is straightforward: How do you check whether user input is valid, and what do you do when it isn't? We will answer that question using JavaScript, focusing on checking digits, ranges, and allowed choices — the three most common validation tasks you will encounter.

SECTION 2

Core Principles of Input Validation

Input validation rests on a few key ideas that apply regardless of the programming language you use. Before diving into JavaScript code, it helps to understand these foundational principles, because they shape every validation decision you will make.

1

Never Trust User Input

Assume every piece of input could be wrong, empty, or even malicious. Always check before you use it. This mindset is called defensive programming.
2

Validate Early, Validate Often

Check input as soon as it arrives. The sooner you catch a problem, the easier it is to give the user a helpful message and avoid deeper bugs in your code.
3

Give Clear Feedback

When input fails validation, tell the user exactly what went wrong and how to fix it. A message like "Please enter a number between 1 and 100" is far better than "Invalid input."
4

Use Whitelisting Over Blacklisting

Define what is allowed (a whitelist) rather than trying to list everything that is forbidden. It is much safer to say "only digits 0–9" than to try blocking every possible non-digit character.
5

Handle Edge Cases

Think about empty strings, extra spaces, very large numbers, and unexpected data types. Edge cases are the unusual inputs that most bugs hide behind.
✦

KEY TAKEAWAY

Think of input validation like a bouncer at a concert. The bouncer checks every ticket before letting someone through the door. If the ticket is fake, expired, or missing, the bouncer does not let the person in — but they explain why and point to the ticket booth. Your code should do the same: check first, explain the problem, and give the user a chance to try again.

SECTION 3

Visual Explanation — The Validation Pipeline

The diagram below shows the typical flow of input validation. User input enters from the left, passes through a series of checks, and either proceeds to be used by the program or is rejected with a helpful error message. Notice how each validation step acts like a filter: only data that passes all checks reaches the "accepted" state.

Input Validation PipelineDATA FLOW →User Inputprompt() / formCHECK 1Not Empty?input.trim() !== ""CHECK 2All Digits?!isNaN(input)CHECK 3In Range?num >= 1 && num <= 100✓ USEAccepted✗ FAIL✗ FAIL✗ FAILError Handling ZoneShow clear error message → Ask user to re-enter input↻ Loop Back to Input
The pipeline shows three sequential checks: not empty, all digits, and in range. Any failure drops to the error handling zone, which informs the user and loops back for another attempt.

This pipeline pattern is the backbone of every validation routine you will write. The exact checks change depending on what you are asking for — an email address requires different rules than a menu choice — but the structure is always the same: receive input, run it through a series of checks, and either accept it or reject it with a clear explanation.

SECTION 4

How It Works — JavaScript Validation Techniques

JavaScript provides several built-in tools for validating user input. Because prompt() always returns a string (or null if the user clicks Cancel), your first job is usually to convert that string into the correct data type and confirm it matches the expected pattern. Below are the key techniques you will use most often.

Checking for Empty or Missing Input

The simplest check is making sure the user actually typed something. The trim() method removes spaces from both ends of a string, so " ".trim() becomes "" (an empty string). You can combine this with a comparison to catch blank entries: if (input === null || input.trim() === ""). This single line handles both a cancelled prompt and a user who just pressed Enter without typing anything.

Checking for Digits — isNaN() and Number()

The function isNaN() returns true if a value is Not-a-Number. To test whether the user entered a valid number, you can write isNaN(input). Meanwhile, Number() converts a string like "42" into the number 42. If the string cannot be converted, Number("abc") returns NaN. A common pattern is: let num = Number(input); if (isNaN(num)) { ... }.

Checking Ranges

Once you have a valid number, checking whether it falls within an acceptable range uses straightforward comparison operators. For example, to ensure a score is between 0 and 100 inclusive, you write num >= 0 && num <= 100. The && operator (logical AND) ensures both conditions must be true simultaneously.

Checking Allowed Choices

When the user must pick from a fixed set of options — such as "rock", "paper", or "scissors" — you can store the allowed values in an array and use the includes() method: ["rock", "paper", "scissors"].includes(input.toLowerCase()). Converting to lowercase with toLowerCase() ensures the check is case-insensitive, so "Rock" and "ROCK" are both accepted.

Looping Until Valid — The while Loop Pattern

Graceful handling usually means giving the user another chance. A while loop is the standard tool for this. You keep prompting until the input passes all your checks. The general structure looks like this: set a flag or condition to false, enter a while loop, prompt the user, validate, and if the input is good, flip the flag to true to exit the loop.

⚠

Watch Out for Infinite Loops

If you forget to update the loop condition inside the loop body, your program will ask for input forever and the browser tab may freeze. Always make sure there is a clear path to exit the loop — for example, by placing the prompt() call inside the loop so the user can eventually provide valid input.

SECTION 5

Detailed Breakdown — Types of Validation

Different situations call for different validation strategies. The diagram below classifies the three main types of validation you will use in this course and shows the JavaScript tools best suited for each one. After the diagram, a reference table provides quick-look syntax for each check.

Three Types of Input ValidationDIGIT VALIDATIONIs it a number?Tools:• isNaN(value)• Number(string)• parseInt(string)Examples:✓ "42" → 42✓ "3.14" → 3.14✗ "abc" → NaN✗ "" → NaN / 0Use when asking forages, scores, quantitiesRANGE VALIDATIONIs it within bounds?Tools:• num >= min• num <= max• && (logical AND)Examples (range 1–10):✓ 5 (in range)✓ 1 (boundary)✗ 0 (too low)✗ 11 (too high)Use when asking forgrades, ratings, menu #sCHOICE VALIDATIONIs it an allowed option?Tools:• array.includes()• toLowerCase()• === strict equalExamples (y / n):✓ "y" (exact match)✓ "N" (after lower)✗ "yes" (not in list)✗ "" (empty)Use when asking foryes/no, menus, game moves
Three columns compare digit validation, range validation, and choice validation. Each column lists the JavaScript tools, valid and invalid examples, and typical use cases.
Validation TypeJavaScript ExpressionReturns true when…
Not emptyinput !== null && input.trim() !== ""User typed at least one non-space character
Is a number!isNaN(input) && input.trim() !== ""String converts to a valid number (avoids empty-string edge case)
Integer onlyNumber.isInteger(Number(input))Number has no decimal part
Within rangenum >= min && num <= maxNumber is between min and max inclusive
Allowed choiceallowedList.includes(input.toLowerCase())Input matches one of the predefined options

Quick-reference table of common validation expressions

SECTION 6

Worked Example — Validating a Test Score

Imagine you are building a grade-book program that asks the user to enter a test score between 0 and 100. The program must reject non-numeric input, out-of-range numbers, and empty entries, then keep asking until it receives a valid score. Let's walk through the solution step by step.

Building a Test-Score Validator

  1. 1

    Step 1 — Set Up the Loop

    We need the program to keep asking until it gets valid input, so we use a while loop controlled by a boolean flag. We declare let valid = false; before the loop and write while (!valid) as the condition. The loop runs as long as valid is false.
    let valid = false; let score; while (!valid) { ... }
  2. 2

    Step 2 — Prompt the User

    Inside the loop, we call prompt() with a clear message explaining what we need. We store the result in a variable called input.
    let input = prompt("Enter a test score (0–100):");
  3. 3

    Step 3 — Check for Empty / Cancelled Input

    If the user clicks Cancel, prompt() returns null. If they press Enter without typing, it returns an empty string. We check for both: if (input === null || input.trim() === ""). If this is true, we display an alert and use continue to skip to the next loop iteration.
    if (input === null || input.trim() === "") { alert("You must enter a value."); continue; }
  4. 4

    Step 4 — Check for Numeric Input

    We convert the string to a number with Number(input) and store it in score. Then we check isNaN(score). If it is Not-a-Number, we alert the user and loop again.
    score = Number(input); if (isNaN(score)) { alert("That is not a number. Please try again."); continue; }
  5. 5

    Step 5 — Check the Range

    Now we know score is a valid number. We check whether it falls between 0 and 100 inclusive. If not, we display a specific message telling the user the acceptable range.
    if (score < 0 || score > 100) { alert("Score must be between 0 and 100."); continue; }
  6. 6

    Step 6 — Accept the Input

    If execution reaches this point, all checks have passed. We set valid = true to exit the loop. After the loop, score holds a guaranteed valid number between 0 and 100 that the rest of the program can safely use.
    valid = true; // Loop exits. score is now safe to use.
💡

Full Code Listing

Here is the complete program assembled from the steps above: let valid = false; let score; while (!valid) { let input = prompt("Enter a test score (0–100):"); if (input === null || input.trim() === "") { alert("You must enter a value."); continue; } score = Number(input); if (isNaN(score)) { alert("That is not a number. Please try again."); continue; } if (score < 0 || score > 100) { alert("Score must be between 0 and 100."); continue; } valid = true; } alert("You entered: " + score);

SECTION 7

Strengths & Limitations of Basic Validation

The validation techniques covered in this lesson are powerful enough for most beginner and intermediate projects, but they do have boundaries. Understanding both the strengths and limitations will help you choose the right tool for each situation and recognize when you need something more advanced.

StrengthsLimitations
Easy to read and write — uses built-in JavaScript functions with clear names.Cannot validate complex patterns (e.g., email format, phone numbers) without regular expressions.
Gives immediate feedback through alert() or console messages, helping users fix mistakes quickly.Using alert() and prompt() blocks the browser — modern apps use HTML form elements instead.
The while-loop pattern is reusable: you can adapt it for any type of input.Client-side validation alone is not secure — a malicious user can bypass it. Server-side checks are also needed.
Combines naturally with if/else, making logic clear and easy to debug.isNaN() has quirks: isNaN("") returns false because Number("") is 0, not NaN. Extra checks are required.
Works in any JavaScript environment — browser, Node.js, or online coding platforms.Does not handle international number formats (e.g., commas as decimal separators) without additional logic.

Strengths vs. limitations of basic input validation in JavaScript

✦

KEY TAKEAWAY

Basic validation with isNaN(), comparison operators, and includes() is like putting a lock on your front door. It stops most problems and is absolutely essential. But just like a house also needs window locks and maybe a security system, a real-world application needs multiple layers of validation — client-side checks for a good user experience and server-side checks for true security.

SECTION 8

Connection to Advanced Validation Techniques

The skills you are learning now form the foundation for every validation system you will encounter in the future. As you progress in programming, the core idea — check input, reject the bad, accept the good — stays the same, but the tools become more powerful and flexible. The table below compares today's basic techniques with advanced approaches you will meet later.

FeatureBasic (This Lesson)Advanced (Future Topics)
Pattern matchingManual checks with isNaN(), comparisons, includes()Regular expressions (regex) — powerful pattern-matching syntax for emails, URLs, dates
User interfaceprompt() and alert() dialogsHTML form inputs with built-in validation attributes (required, min, max, pattern)
SecurityClient-side only — can be bypassedServer-side validation, input sanitization, parameterized database queries
Error displaySimple alert messagesInline error messages next to specific form fields, color-coded borders, real-time feedback
ScaleOne input at a timeValidation libraries (Yup, Joi, Zod) that validate entire objects with complex rules

Basic vs. advanced validation techniques

Even professional developers who use advanced libraries still rely on the same logical thinking you are developing now. When you write if (isNaN(score)), you are practicing the exact same guard clause pattern that appears in every production codebase. Mastering these basics will make learning frameworks and libraries much easier down the road.

SECTION 9

Practice Problems

Test your understanding with these five problems. They start with a concept check and build toward more complex scenarios. Try writing your answers in a code editor or on paper before revealing the solution.

Question 1: CONCEPTUAL

Explain in your own words why isNaN("") returns false even though an empty string is clearly not a meaningful number. Why does this matter for input validation?
Show answer
JavaScript coerces the empty string to a number before checking. Number("") evaluates to 0, and 0 is a valid number, so isNaN returns false. This matters because a blank entry would silently become 0 in your program, producing incorrect results without any error message. That is why you should always check for an empty string before calling isNaN() — for example, input.trim() !== "" && !isNaN(input).

Question 2: BASIC CALCULATION

Write a JavaScript expression that checks whether the variable age (already converted to a number) is a valid age for a high school student (between 14 and 18 inclusive). What does your expression evaluate to if age is 16? What about 21?
Show answer
The expression is age >= 14 && age <= 18. When age is 16, both conditions are true (16 ≥ 14 is true, 16 ≤ 18 is true), so the overall expression evaluates to true. When age is 21, the second condition (21 ≤ 18) is false, so the entire expression evaluates to false because && requires both sides to be true.

Question 3: INTERMEDIATE

A menu program displays three options: 1) Play, 2) Settings, 3) Quit. Write a complete validation loop using prompt() that keeps asking the user until they enter 1, 2, or 3. Use an array and includes() in your solution.
Show answer
Here is one solution: let choices = ["1", "2", "3"]; let choice = ""; while (!choices.includes(choice)) { choice = prompt("Choose an option:\n1) Play\n2) Settings\n3) Quit"); if (choice === null) choice = ""; choice = choice.trim(); if (!choices.includes(choice)) { alert("Invalid choice. Please enter 1, 2, or 3."); } } Notice that we compare strings ("1", "2", "3") rather than numbers, because prompt() returns a string. We also handle the null case from a cancelled prompt and trim whitespace. After the loop, choice is guaranteed to be "1", "2", or "3".

Question 4: APPLIED

You are building a temperature converter. The user first enters a temperature (any number), then chooses the unit by typing "C" for Celsius or "F" for Fahrenheit. Write validation code for both inputs. The temperature should be a valid number between −273.15 and 10000, and the unit must be either "C" or "F" (case-insensitive). Show both validation loops.
Show answer
For the temperature: let temp; let validTemp = false; while (!validTemp) { let t = prompt("Enter temperature (−273.15 to 10000):"); if (t === null || t.trim() === "") { alert("Please enter a value."); continue; } temp = Number(t); if (isNaN(temp)) { alert("Not a valid number."); continue; } if (temp < -273.15 || temp > 10000) { alert("Out of range."); continue; } validTemp = true; } For the unit: let unit = ""; let allowedUnits = ["c", "f"]; while (!allowedUnits.includes(unit)) { let u = prompt("Enter unit (C or F):"); if (u === null) u = ""; unit = u.trim().toLowerCase(); if (!allowedUnits.includes(unit)) { alert("Please type C or F."); } } The first loop uses digit, empty-check, and range validation together. The second loop uses choice validation with includes() and toLowerCase() for case-insensitive matching.

Question 5: CRITICAL THINKING

A classmate writes this validation check: let n = prompt("Enter a positive integer:"); if (n > 0) { /* use n */ } Identify at least three problems with this code. For each problem, explain what could go wrong and how to fix it.
Show answer
Problem 1: The code never converts the string to a number. JavaScript's > operator coerces the string, but this can produce unexpected results (e.g., "3abc" > 0 is false, but "" > 0 is also false without explaining why). Fix: use Number(n) explicitly. Problem 2: There is no check for non-numeric input. If the user types "hello", Number("hello") is NaN, and NaN > 0 is false, so the code silently skips the block with no feedback. Fix: check isNaN() first and alert the user. Problem 3: The code does not check for an integer — 3.7 would pass the check even though the prompt says "positive integer." Fix: add Number.isInteger(). Bonus: There is no loop, so the user only gets one chance. If they enter invalid data, the program just moves on with no valid value. Fix: wrap the validation in a while loop.

SUMMARY

Lesson Summary

Summary

Input validation is the practice of checking user input before your program uses it. In this lesson you learned three core types: digit validation using isNaN() and Number() to confirm the input is numeric, range validation using comparison operators like >= and <= with the && operator to ensure a number falls within acceptable bounds, and choice validation using includes() and toLowerCase() to match input against a list of allowed options.

You also learned the importance of graceful error handling — giving users clear feedback and a chance to try again using a while loop pattern. The guiding principles are to never trust user input, validate early, use whitelisting over blacklisting, and always handle edge cases like empty strings and null values. These fundamentals will serve as the building blocks for every form, application, and security check you write throughout your programming career.

Varsity Tutors • Computer Programming 1 (JavaScript) • Input Validation — I can validate user input (digits, ranges, allowed choices) and handle invalid cases gracefully.