5.2 Module 5 · Forms & Input Handling

Input Validation

Learn how to check user data before acting on it — catching empty fields, invalid types, wrong formats, and out-of-range values to keep your application safe and reliable.

1

Definition

Input Validation in JavaScript is the process of checking whether user-provided data is correct, complete, and in the expected format before processing or submitting it.

Validation protects your application from bad data — an empty required field, letters where a number is expected, or an age of 999. It also gives users helpful feedback so they can correct mistakes before submitting.

2

Simple Way

Input validation asks "is this data actually usable?" — three fundamental questions cover most cases:

Empty? value.trim() === "" — did the user leave a required field blank?
Number? isNaN(value) — did the user type letters in a numeric field?
Range? num < 1 || num > 120 — is the number within acceptable bounds?
Format? Does it match an expected pattern — email, phone, password length?
3

Code Examples

Example 1 — Empty Field Check
<input id="nameField" type="text" placeholder="Your name">
<button onclick="validate()">Submit</button>
<p id="msg1"></p>

<script>
  function validate() {
    let name = document.getElementById("nameField").value.trim();
    let msg  = document.getElementById("msg1");

    if (name === "") {
      msg.textContent = "❌ Name is required.";
      msg.style.color = "red";
    } else {
      msg.textContent = "✓ Hello, " + name + "!";
      msg.style.color = "green";
    }
  }
</script>
Live Preview
Explanation
  • Always call .trim() first — a field with only spaces passes === "" without trim
  • Comparing to "" is the simplest and most reliable empty check for string inputs
  • Show the error message inline near the field — never rely on alerts for validation feedback
Example 2 — Case-Insensitive Comparison
<input id="langField" type="text" placeholder="Enter a language">
<button onclick="checkLang()">Check</button>
<p id="msg2"></p>

<script>
  function checkLang() {
    let input = document.getElementById("langField").value.trim();
    let msg   = document.getElementById("msg2");

    // toLowerCase normalises: "JavaScript", "JAVASCRIPT", "javascript" all match
    if (input.toLowerCase() === "javascript") {
      msg.textContent = "✓ Correct! That's what we're learning.";
      msg.style.color = "green";
    } else {
      msg.textContent = "✗ Try: JavaScript";
      msg.style.color = "red";
    }
  }
</script>
Live Preview
Explanation
  • .toLowerCase() normalises the input before comparing — "JavaScript", "JAVASCRIPT", and "javascript" all match
  • Always lowercase both sides if you want truly case-insensitive comparison
  • Alternatively .toUpperCase() works the same way — pick one and be consistent
Example 3 — Number & Range Validation
<input id="ageField" type="text" placeholder="Enter age">
<button onclick="checkAge()">Check Age</button>
<p id="msg3"></p>

<script>
  function checkAge() {
    let raw = document.getElementById("ageField").value.trim();
    let age = Number(raw);
    let msg = document.getElementById("msg3");

    if (raw === "") {
      msg.textContent = "❌ Age is required.";
    } else if (isNaN(age)) {
      msg.textContent = "❌ Age must be a number, not text.";
    } else if (age < 1 || age > 120) {
      msg.textContent = "❌ Age must be between 1 and 120.";
    } else {
      msg.textContent = "✓ Valid age: " + age;
    }
    msg.style.color = msg.textContent.startsWith("✓") ? "green" : "red";
  }
</script>
Live Preview
Explanation
  • isNaN() returns true when the value cannot be interpreted as a number — try typing "abc"
  • Check empty first, then isNaN, then range — each guard is more specific than the last
  • This layered validation gives the user precise feedback for every failure case
Example 4 — Validating Multiple Fields Together
function validateForm(name, age, password) {
  let errors = [];

  if (name.trim() === "") {
    errors.push("Name is required");
  }

  let n = Number(age);
  if (isNaN(n) || n < 1 || n > 120) {
    errors.push("Age must be a number between 1 and 120");
  }

  if (password.length < 6) {
    errors.push("Password must be at least 6 characters");
  }

  return errors; // empty array = all valid
}

let result = validateForm("Aman", "25", "pass");
console.log(result.length === 0 ? "All valid!" : result);
Output
Click ▶ Run to execute
Explanation
  • Collect all errors into an array — show every problem at once rather than one at a time
  • Return an empty array when everything passes — an empty array is falsy-friendly for checks
  • A dedicated validation function is reusable and keeps the submit handler clean
4

Real-Life Example

Think of a job application form — the HR officer rejects invalid entries exactly like JavaScript validation does:

Empty check
Name field blank → "Please enter your full name"
isNaN
Age field has "twenty" → "Age must be a number"
Range check
Age is 200 → "Age must be between 18 and 65"
Format check
Email missing "@" → "Enter a valid email address"
5

HTML + JavaScript Example

Click ▶ Preview — try submitting with empty fields, a non-numeric age, or a short password to see each validation rule fire.

Live in Browser — Registration Form with Validation
<!DOCTYPE html>
<html>
<head><title>Input Validation</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">

  <h2>Register</h2>

  <div style="display:flex;flex-direction:column;gap:10px;max-width:320px">

    <input id="regName" type="text" placeholder="Full name"
      style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;font-size:1rem">

    <input id="regAge" type="text" placeholder="Age"
      style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;font-size:1rem">

    <input id="regPass" type="password" placeholder="Password (min 6 chars)"
      style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;font-size:1rem">

    <button onclick="register()"
      style="padding:9px;background:#f7df1e;border:none;border-radius:6px;
             cursor:pointer;font-weight:700;font-size:1rem">
      Submit
    </button>
  </div>

  <div id="errors"
    style="margin-top:14px;font-size:0.9rem;line-height:2;color:red">
  </div>
  <p id="success" style="color:green;margin-top:8px;font-weight:600"></p>

  <script>
    function register() {
      let name = document.getElementById("regName").value.trim();
      let age  = document.getElementById("regAge").value.trim();
      let pass = document.getElementById("regPass").value;
      let errs = [];

      if (name === "")          errs.push("Name is required.");
      if (age  === "")          errs.push("Age is required.");
      else if (isNaN(Number(age))) errs.push("Age must be a number.");
      else if (Number(age) < 1 || Number(age) > 120) errs.push("Age must be 1–120.");
      if (pass.length < 6)     errs.push("Password must be at least 6 characters.");

      let errBox = document.getElementById("errors");
      let ok     = document.getElementById("success");

      if (errs.length > 0) {
        errBox.innerHTML = errs.map(e => "❌ " + e).join("<br>");
        ok.textContent   = "";
      } else {
        errBox.innerHTML = "";
        ok.textContent   = "✓ Registered successfully, " + name + "!";
      }
    }
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Password required check
Starter code
<input id="pwd" type="password" placeholder="Password">
<button onclick="checkPwd()">Submit</button>
<p id="pwdMsg"></p>

<script>
  function checkPwd() {
    // show "Password required" if empty
  }
</script>
  • Read document.getElementById("pwd").value and call .trim()
  • If empty, set the message to "❌ Password required" in red
  • Otherwise display "✓ Password accepted" in green
Medium Task 2 — Name & age multi-field validator
Starter code
<input id="vName" type="text" placeholder="Name">
<input id="vAge"  type="text" placeholder="Age">
<button onclick="validate()">Check</button>
<p id="vMsg"></p>
  • Check name is not empty (use .trim())
  • Check age is a valid number (use isNaN(Number(age)))
  • Show all error messages in one <p> — use an array and .join()
7

MCQs

Q1
Which function returns true when a value cannot be parsed as a number?
console.log(isNaN("hello")); // ?
console.log(isNaN("42"));    // ?
console.log(isNaN(42));      // ?
Output
Run it to verify
  • A checkNumber()
  • B isNaN()
  • C parseInt()
  • D Number()
💡 B is correct. isNaN() coerces its argument and returns true if the result is NaN. isNaN("hello")true; isNaN("42")false (it converts "42" to 42 first).
Q2
How do you make a string comparison case-insensitive?
let input = "JavaScript";

console.log(input.toLowerCase() === "javascript"); // ?
console.log(input.toUpperCase() === "JAVASCRIPT"); // ?
Output
Run it to verify
  • A .toUpperCase() only
  • B .toLowerCase() only
  • C Either .toLowerCase() or .toUpperCase() (normalise both sides)
  • D Neither — JavaScript is always case-sensitive
💡 C is correct. Both work — the key is to normalise both the input and the target string to the same case before comparing. The conventional choice is .toLowerCase().
Q3
What does this condition check?
let input = "  ";

if (input.trim() === "") {
  console.log("Empty!");
} else {
  console.log("Has content");
}
Output
Run it to verify
  • A Number validation
  • B Empty or whitespace-only field check
  • C String type conversion
  • D Boolean check
💡 B is correct. .trim() removes all leading and trailing whitespace. A string of only spaces (" ") becomes "" after trim — so this check catches both genuinely empty fields and ones filled with spaces.
8

Pro Tips & Extra Knowledge

  • 01

    Always chain .trim() before any comparison — a field containing only spaces will pass === "" without it:

    trim() catches space-only input
    let input = "   "; // looks like spaces, user thinks it's empty
    
    // ✗ Wrong — passes because the string is truthy
    if (input === "") console.log("empty"); // does NOT print
    
    // ✓ Correct — trim first
    if (input.trim() === "") console.log("empty (after trim)"); // prints
    Output
    Click ▶ Run to execute
  • 02

    Combine multiple checks with || for concise validation — show one clear error message:

    Combined validation
    let name = "  ";
    let age  = "abc";
    
    if (name.trim() === "" || isNaN(Number(age))) {
      console.log("Invalid: name is empty or age is not a number");
    } else {
      console.log("Valid inputs");
    }
    Output
    Click ▶ Run to execute
  • 03

    Use Number() — not parseInt() — for strict number validation. parseInt("25abc") returns 25 silently, which is not what you want:

    Number() vs parseInt() for validation
    let input = "25abc";
    
    console.log(parseInt(input));  // 25   — parses partial! not safe for validation
    console.log(Number(input));    // NaN  — strict, fails on mixed input
    console.log(isNaN(Number(input))); // true — correctly detected as invalid
    Output
    Click ▶ Run to execute
  • 04

    Frontend validation is for user experience — never rely on it alone. Always validate on the backend too, since JavaScript can be bypassed in the browser.

Mini Challenge

"123abc" is a mixed string — will isNaN treat it as a number or not? Think before running.

What does this print?
let value = "123abc";

console.log(isNaN(value));
console.log(Number(value));
console.log(isNaN(Number(value)));
Output
Think first, then run!
Step-by-Step Explanation
// value = "123abc"

// Line 1: isNaN(value)
//   isNaN() coerces its argument to a number first: Number("123abc") = NaN
//   isNaN(NaN) = true
//   Output → true

// Line 2: Number(value)
//   Number("123abc") — cannot fully parse, returns NaN
//   Output → NaN

// Line 3: isNaN(Number(value))
//   Number("123abc") = NaN
//   isNaN(NaN) = true
//   Output → true

// Final output:
//   true
//   NaN
//   true

// Key takeaway:
//   isNaN("123abc") and isNaN(Number("123abc")) both return true
//   because the string contains non-numeric characters.
//   Compare: Number("123") = 123 (valid), Number("123abc") = NaN (invalid)
//
//   For strict validation, prefer: isNaN(Number(input))
//   because it is explicit about what conversion is being applied.