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.
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.
Input validation asks "is this data actually usable?" — three fundamental questions cover most cases:
value.trim() === "" — did the user leave a required field blank?
isNaN(value) — did the user type letters in a numeric field?
num < 1 || num > 120 — is the number within acceptable bounds?
<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>
.trim() first — a field with only spaces passes === "" without trim"" is the simplest and most reliable empty check for string inputs<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>
.toLowerCase() normalises the input before comparing — "JavaScript", "JAVASCRIPT", and "javascript" all match.toUpperCase() works the same way — pick one and be consistent<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>
isNaN() returns true when the value cannot be interpreted as a number — try typing "abc"isNaN, then range — each guard is more specific than the lastfunction 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);
Think of a job application form — the HR officer rejects invalid entries exactly like JavaScript validation does:
Click ▶ Preview — try submitting with empty fields, a non-numeric age, or a short password to see each validation rule fire.
<!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>
<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>
document.getElementById("pwd").value and call .trim()<input id="vName" type="text" placeholder="Name">
<input id="vAge" type="text" placeholder="Age">
<button onclick="validate()">Check</button>
<p id="vMsg"></p>
.trim())isNaN(Number(age)))<p> — use an array and .join()true when a value cannot be parsed as a number?
console.log(isNaN("hello")); // ?
console.log(isNaN("42")); // ?
console.log(isNaN(42)); // ?
isNaN() coerces its argument and returns true if the result is NaN. isNaN("hello") → true; isNaN("42") → false (it converts "42" to 42 first).
let input = "JavaScript";
console.log(input.toLowerCase() === "javascript"); // ?
console.log(input.toUpperCase() === "JAVASCRIPT"); // ?
.toLowerCase().
let input = " ";
if (input.trim() === "") {
console.log("Empty!");
} else {
console.log("Has content");
}
.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.
Always chain .trim() before any comparison — a field containing only spaces will pass === "" without it:
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
Combine multiple checks with || for concise validation — show one clear error message:
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");
}
Use Number() — not parseInt() — for strict number validation. parseInt("25abc") returns 25 silently, which is not what you want:
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
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.
"123abc" is a mixed string — will isNaN treat it as a
number or not? Think before running.
let value = "123abc";
console.log(isNaN(value));
console.log(Number(value));
console.log(isNaN(Number(value)));
// 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.