SA-21/06, C-11, Asapur, Varanasi, UP support@kamaldnp.com +91 8318013442
JavaScript
1. JavaScript Tutorial for Beginners — Learn JS from Scratch 2. Where to Put JavaScript Code — Head, Body or .js File 3. JavaScript Output Methods — alert, innerHTML, console.log 4. JavaScript Syntax Explained — Statements & Rules 5. JavaScript Comments — How to Write // and /* */ 6. JavaScript Variables — var, let, const Explained 7. JavaScript Operators — Arithmetic, Comparison, Logical 8. JavaScript Data Types — string, number, object, array 9. JavaScript Functions Tutorial — Parameters & Return Values 10. JavaScript Objects — Properties, Methods & this Keyword 11. JavaScript Scope — Global, Local & Block Scope Explained 12. JavaScript Events — addEventListener with Examples 13. JavaScript Strings — Methods, slice, replace & Templates 14. JavaScript Numbers — parseInt, toFixed, NaN Explained 15. JavaScript Arrays — Create, Read, push, pop & More 16. JavaScript Array Methods — map, filter, forEach, find 17. JavaScript Date Object — new Date(), getFullYear & More 18. JavaScript Math Object — random, round, floor, ceil 19. JavaScript if else — Conditions with Examples 20. JavaScript switch Statement — case, break, default 21. JavaScript for Loop — for, for...of, for...in Examples 22. JavaScript while Loop — while & do...while Explained 23. JavaScript Type Conversion — Number, String, Boolean 24. JavaScript try catch — Error Handling with finally 25. JavaScript JSON — stringify & parse with Examples 26. JavaScript Arrow Functions — => Syntax & this 27. JavaScript Classes — Constructor & Objects Explained 28. JavaScript Promises & async/await Explained Simply 29. JavaScript DOM Tutorial — Find & Change Page Elements 30. JavaScript Form Validation Tutorial with Examples 31. JavaScript Fetch API Tutorial — fetch() with Examples 32. JavaScript localStorage — setItem, getItem Explained 33. JavaScript Timers — setTimeout & setInterval Examples 34. JavaScript Regular Expressions — test() & match() Guide 35. JavaScript Debugging — console.log & Fixing Errors
Final Test — Certificate ₹10
Try this code live
Lesson 30 of 35

JavaScript Form Validation Tutorial with Examples

4 min read · Free · No login needed

A form is a door into your website. Whatever a visitor types — a name, a mobile number, an email — walks straight through that door. If you do not check it first, bad data gets in: an empty name, a nine-digit mobile number, an email with no @. Form validation is the guard at the door: it checks every value before the form is allowed through, and shows a clear error next to anything wrong.

Diagram — see how it fits together
Diagram: JavaScript Form Validation

Think of an admission desk. The clerk does not send a half-filled form to the office — she checks it at the desk, points at the empty line, and asks the student to fill it in. JavaScript does the same job on the page, instantly, before anything is sent to the server. Checking at the door is faster and kinder than finding the mistake later.

Reading values — .value

let name = document.getElementById("name").value;
let mobile = document.getElementById("mobile").value;
let email = document.getElementById("email").value;

Every input has a .value — always a string, even for numbers (remember the type conversion lesson). For a checkbox, use .checked instead: it is true or false. For a dropdown (<select>), .value gives the value of the option the user picked.

Checking values — the common rules

  • Empty: if (name.trim() === "") — trim() removes spaces from both ends, so a box with only spaces still counts as empty.
  • Length: if (mobile.length !== 10) — an Indian mobile number has exactly 10 digits.
  • Numbers only: if (isNaN(Number(mobile))) — letters in a mobile number are not allowed.
  • Email: if (!email.includes("@")) — a simple check that catches the most common mistake. A full email check uses a pattern, but @ plus a dot is enough for a first version.
Note: JavaScript validation is for the user's convenience — it gives instant feedback. It is not security. Anyone can turn JavaScript off, so the server must check the same rules again. Never trust the browser alone with important data.

Showing errors and stopping the submit

function validate() {
  let error = document.getElementById("error");
  if (name.trim() === "") {
    error.textContent = "Please type your name.";
    return false;
  }
  error.textContent = "";
  return true;
}

Show the error in a red paragraph next to the form, and clear it when the problem is fixed. When the form uses a real submit button, the form's onsubmit must return false to stop the page from sending — or you can call event.preventDefault(). In our example the button is type="button", so it never submits by itself: the JavaScript decides what happens, and shows a green success message when everything is right.

Tip: Remember it like this: check at the door, not after the guest is inside. Validate on the button click, show the first error you find, and clear errors as soon as they are fixed — one clear message beats five confusing ones.

Common mistakes

  • Forgetting trim() — a name of only spaces passes an empty check. Always trim first.
  • Checking length on a number — mobile.length works because the value is a string; if you converted it with Number() first, .length is undefined.
  • Validating only on submit — also check when the user leaves a field, so the error appears while they are still looking at it.
  • Showing five errors at once — fix the first one, then show the next. One message at a time is kinder.
  • Trusting browser validation alone — the server must re-check everything, because JavaScript can be switched off.

Remember

  • Read inputs with .value (strings) and checkboxes with .checked.
  • Common checks: empty (trim() === ""), length, numbers only, email has @.
  • Show errors in red next to the form; clear them when fixed.
  • Stop a bad submit with return false or event.preventDefault().
  • Check at the door, not after the guest is inside.

Example explained

  • let name = document.getElementById("name").value.trim(); — reads the name and trims the spaces, so " " counts as empty.
  • if (name === "") { showError("Please type your name."); return; } — the first check stops the function at once, so only one error is ever shown.
  • if (mobile.length !== 10 || isNaN(Number(mobile))) — the mobile must be exactly 10 characters and all digits.
  • if (!email.includes("@")) — the email must contain an @. Simple, but it catches the most common mistake.
  • document.getElementById("out").style.color = "green"; — when every check passes, the message turns green: the form is accepted.

Example

Example
<!DOCTYPE html>
<html>
<head>
<title>Admission Form — Validation</title>
<style>
body { font-family: Verdana, sans-serif; background-color: #fff8e1; }
h1 { color: #b45309; text-align: center; }
.card { background-color: white; border: 2px solid #f59e0b; padding: 16px; width: 360px; margin: 20px auto; }
button { background-color: #b45309; color: white; border: none; padding: 10px 18px; font-size: 16px; }
input { width: 200px; padding: 6px; margin: 4px 0; }
#out { font-weight: bold; }
</style>
</head>
<body>

<h1>Admission Form</h1>
<div class="card">
<p>Name: <input id="name" type="text" value="Priya"></p>
<p>Mobile: <input id="mobile" type="text" value="9876543210"></p>
<p>Email: <input id="email" type="text" value="priya@example.com"></p>
<p><button onclick="submitForm()">Submit admission</button></p>
<p id="out">Fill the form and click Submit. Try a wrong value — the error appears in red.</p>
</div>

<script>
function submitForm() {
  let out = document.getElementById("out");
  let name = document.getElementById("name").value.trim();
  let mobile = document.getElementById("mobile").value.trim();
  let email = document.getElementById("email").value.trim();
  out.style.color = "red";
  if (name === "") {
    out.textContent = "Please type your name.";
    return;
  }
  if (mobile.length !== 10 || isNaN(Number(mobile))) {
    out.textContent = "Mobile must be 10 digits, numbers only.";
    return;
  }
  if (!email.includes("@")) {
    out.textContent = "Email must contain @.";
    return;
  }
  out.style.color = "green";
  out.textContent = "Thank you, " + name + "! Your admission form is accepted.";
}
</script>

</body>
</html>

Output

Output — how it looks in the browser
Output of JavaScript Form Validation Tutorial with Examples

Try it yourself — live editor

Change the code below and press Run to see the result instantly. No file to save, no login needed.

Result

Frequently asked questions

The questions learners ask most about this lesson — read the question, then open it to see the answer.

1. Why validate a form in JavaScript before sending it?

Checking at the door is faster and kinder than finding the mistake later — errors are shown instantly, before anything reaches the server.

2. How do I check whether a name field is really empty?

Use name.trim() === "" — trim removes spaces from both ends, so a box with only spaces still counts as empty.

3. What does .value give for an input?

Always a string, even for numbers — and for a checkbox, use .checked instead, which is true or false.

Why learn this yourself — and not just ask AI?

AI can write code for you, but it cannot think for you. When you learn HTML yourself, your brain builds the real skill: you understand why a page looks the way it does, you can fix it when it breaks, and you can answer it in an exam or an interview without help. That is the skill that gets you a job — not a copied answer.

Get certified — just ₹10

Finish all 35 lessons, pass the test (80%), pay ₹10 and get your certificate.

Take the test

Prefer watching? Video courses teach the same topics step by step.

Go further with a full course

Free tutorials teach you the basics. Our paid courses add live projects, mentorship and a certificate.

Core Python Programming – 3 Month Complete Course
₹700
View
AI Prompt Engineering Webinar 2026
View
Full Stack PHP Development Course 2026
₹3,000
View
Browse all courses
JavaScript — Lessons
1. JavaScript Tutorial for Beginners — Learn JS from Scratch 2. Where to Put JavaScript Code — Head, Body or .js File 3. JavaScript Output Methods — alert, innerHTML, console.log 4. JavaScript Syntax Explained — Statements & Rules 5. JavaScript Comments — How to Write // and /* */ 6. JavaScript Variables — var, let, const Explained 7. JavaScript Operators — Arithmetic, Comparison, Logical 8. JavaScript Data Types — string, number, object, array 9. JavaScript Functions Tutorial — Parameters & Return Values 10. JavaScript Objects — Properties, Methods & this Keyword 11. JavaScript Scope — Global, Local & Block Scope Explained 12. JavaScript Events — addEventListener with Examples 13. JavaScript Strings — Methods, slice, replace & Templates 14. JavaScript Numbers — parseInt, toFixed, NaN Explained 15. JavaScript Arrays — Create, Read, push, pop & More 16. JavaScript Array Methods — map, filter, forEach, find 17. JavaScript Date Object — new Date(), getFullYear & More 18. JavaScript Math Object — random, round, floor, ceil 19. JavaScript if else — Conditions with Examples 20. JavaScript switch Statement — case, break, default 21. JavaScript for Loop — for, for...of, for...in Examples 22. JavaScript while Loop — while & do...while Explained 23. JavaScript Type Conversion — Number, String, Boolean 24. JavaScript try catch — Error Handling with finally 25. JavaScript JSON — stringify & parse with Examples 26. JavaScript Arrow Functions — => Syntax & this 27. JavaScript Classes — Constructor & Objects Explained 28. JavaScript Promises & async/await Explained Simply 29. JavaScript DOM Tutorial — Find & Change Page Elements 30. JavaScript Form Validation Tutorial with Examples 31. JavaScript Fetch API Tutorial — fetch() with Examples 32. JavaScript localStorage — setItem, getItem Explained 33. JavaScript Timers — setTimeout & setInterval Examples 34. JavaScript Regular Expressions — test() & match() Guide 35. JavaScript Debugging — console.log & Fixing Errors
Final Test — Certificate ₹10

🤖 KAMALDNP AI Assistant

Ask about courses, website & more

Hi! I'm KAMALDNP AI Assistant. Ask me about our courses, website features, or anything else! 😊
Please wait 5s...
🤖 KAMALDNP Assistant ✕

Request human callback:

🔐 Login Required
✕

Please log in to download. You will stay on this page after logging in!

New here? Register now →