Popular Searches
Popular Course Categories
Popular Courses

Form validation

Form validation

31 mins DOM & Browser APIs

Form validation in React JS

Course: React JS Training

Topic: Form validation

Course Link: React JS Training

Demo Link: Register for a Course Demo


1. Why form validation matters

Almost every real website needs to collect something from the user: a name, an email address, a password, a phone number, an order quantity. The form is the doorway through which this data enters your application, and form validation is the check that happens at the door. Without validation, a program happily accepts an empty name, an email like hello with no @ sign, a password of two letters, or a pincode with letters in it. The page may look fine for a second, but the data is broken, and broken data causes real failures later: a login system that cannot find the account, a report that shows nonsense totals, a database slowly filling with junk rows.

Validation protects the project in three ways:

  • Better user experience. The user learns instantly that name@example is missing a dot, instead of discovering the mistake after the page reloads or the request fails on the server.
  • Cleaner data. The values your JavaScript, your backend and your database receive actually match what they expect.
  • Safety and stability. Many attacks work by sending unexpected input to a server. Checked input is one layer of defence, although it must never be the only one.

For this course, form validation is also a milestone skill: it is the first place where the DOM, events, conditionals, strings and regular expressions all work together on a realistic problem. When you later move to React, you will handle forms through state and controlled components, but the rules you learn here — what to check, when to check it, how to show an error — stay exactly the same.

2. Form validation in simple words

Form validation means checking the values a user has typed into a form against a set of rules, and refusing to accept the form until every rule passes.

Think of a security guard outside an event. The guard does not decide who gets in based on mood; there is a list of rules: ticket present, ticket not expired, one person per ticket. Anyone who fails a rule is stopped at the door and told exactly why. Validation works the same way for forms: rules are defined in advance, the user's input is tested against them, and failing input is rejected with a clear message before the data moves on.

Typical rules look like this:

  • This field is required — it cannot be empty.
  • This value must look like an email address, a phone number or a pincode.
  • This value must have a minimum and maximum length.
  • This number must be inside a range, for example age between 18 and 60.
  • These two fields must match, for example password and confirm password.

There are two ways to apply these rules in the browser, and they work together:

  • HTML-only validation. The right attributes on <input> elements make the browser do the checking for you, no JavaScript needed.
  • JavaScript validation. You listen to the submit event, inspect the values yourself and show your own messages. This is needed whenever a rule cannot be expressed in HTML, such as "confirm password must equal password".

3. Key terms

  • Constraint: a single rule attached to a field, such as "required" or "at least 8 characters".
  • Client-side validation: checking done in the browser, before anything is sent anywhere. Fast and friendly, but under the user's control.
  • Server-side validation: checking done again on the server after the data arrives. Slower from the user's view, but the only check that cannot be bypassed.
  • Default action: what the browser does by itself. For a form, the default action on submit is to send the data and reload the page. JavaScript can cancel it.
  • preventDefault(): the method that cancels the browser's default action, usually so we can validate first.
  • ValidityState: the object the browser keeps for every input field, with one true/false property per possible rule violation.
  • validationMessage: the ready-made sentence the browser generates for a field that currently fails a constraint.
  • setCustomValidity(): a method to attach your own rule or your own error text to a field.
  • Regular expression (regex): a small pattern language used to describe what valid text should look like, for example "digits only" or "contains an @ followed by a dot".
  • Inline error message: a short text shown next to the field that failed, instead of one alert box at the end. The preferred modern pattern.

4. Where validation happens: client side and server side

Beginners often assume one check is enough. It is not. The two layers do different jobs:

AspectClient-side validationServer-side validation
Where it runsIn the user's browserOn the server, after the data is sent
Speed of feedbackInstant, per keystroke or per fieldOnly after a round trip
Can it be bypassed?Yes — the user can disable JavaScript or send requests directlyNo — it is the final authority
Best used forFast, friendly feedback and a smooth experienceSecurity, data integrity, business rules
Typical toolsHTML attributes, CSS, JavaScriptBackend language and framework of the project
The rule every developer memorises: never trust the client. Client-side validation is for the user's comfort; server-side validation is for the system's safety. In a full-stack career you will write both; in this module we master the client side.

5. Built-in HTML5 validation attributes

The cheapest validation is the kind you get for free. When a field carries certain attributes, the browser blocks submission and shows a small warning bubble if the rule is broken — no JavaScript required.

AttributeRule it enforcesExample
requiredField must not be emptyrequired
type="email"Value must contain a valid email shapetype="email"
type="number"Value must be a numbertype="number"
min / maxNumber must be inside the rangemin="18" max="60"
minlength / maxlengthText length limitsminlength="8"
patternValue must match a regular expressionpattern="[0-9]{10}"
titleNot a rule — the hint shown when pattern failstitle="10-digit phone"

A small form that validates itself:

<form>
  <label for="email">Email</label>
  <input id="email" type="email" required placeholder="[email protected]">

  <label for="age">Age</label>
  <input id="age" type="number" min="18" max="60" required>

  <label for="pin">Pincode</label>
  <input id="pin" type="text" pattern="[1-9][0-9]{5}" title="6-digit pincode">

  <button type="submit">Join</button>
</form>

Press Join with an empty email and the browser refuses to submit, highlights the first broken field and explains the problem. This is genuine validation, and for simple rules it is often all you need.

Two habits to build now:

  • Always connect a <label> to its field with for and id. Labels are part of usable forms, not decoration.
  • Use type="email", type="number", type="tel" and friends rather than type="text" everywhere — the correct type gives you a constraint and the right mobile keyboard.

6. Showing valid and invalid fields with CSS

CSS can style the result of validation without any JavaScript, because browsers expose pseudo-classes that reflect the constraint state:

  • :valid — matches fields whose current value passes all constraints.
  • :invalid — matches fields that currently fail at least one constraint.
  • :required / :optional — matches fields with or without the required attribute.
input:valid {
  border: 2px solid seagreen;
}

/* red only after the user has typed in and left the field */
input:user-invalid {
  border: 2px solid crimson;
}

One warning: :invalid is true before the user types anything, because an empty required field is already invalid. If you style input:invalid directly, the whole form turns red on page load. The calmer pattern is to add a class with JavaScript when a field loses focus, and style only touched fields:

/* JavaScript adds "touched" when the user leaves a field */
input.touched:invalid {
  border: 2px solid crimson;
}

7. The Constraint Validation API, step by step

HTML attributes and CSS are the visible layer. Underneath them sits a set of JavaScript objects and methods, usually called the Constraint Validation API. This is what you use when you want the browser's rules but your own interface.

Every input element carries a validity object. Each property answers one yes/no question about the current value:

PropertyTrue when…
valueMissinga required field is empty
typeMismatchthe value does not fit the type, for example a bad email
patternMismatchthe value does not match the pattern attribute
tooShort / tooLongthe value is shorter than minlength or longer than maxlength
rangeUnderflow / rangeOverflowthe number is below min or above max
stepMismatchthe number does not fit the step value
validnone of the rules are broken

A validation flow, from click to acceptance, reads like this:

  1. The user fills the form and clicks the submit button.
  2. The browser fires a submit event on the <form> element.
  3. Our listener runs before any data is sent anywhere.
  4. We call event.preventDefault() to cancel the automatic submission and page reload.
  5. For each field, we inspect field.validity or our own rules and record any failures.
  6. If anything failed, we show messages, focus the first broken field and stop.
  7. If everything passed, we proceed — for now a success message, later a fetch() request.

Three methods complete the picture:

  • field.checkValidity() — returns true if the value passes every constraint, false otherwise, without showing anything.
  • field.validationMessage — the browser's own explanation of the first failing rule, ready to display.
  • form.reportValidity() — runs the same checks and shows the browser's bubbles for you.

And when the failing rule is one HTML cannot express, setCustomValidity() attaches your verdict to the field, so the browser treats it as if it were a built-in rule. The classic case is confirming a password:

const password = document.querySelector("#password");
const confirmPassword = document.querySelector("#confirm");

confirmPassword.addEventListener("input", function () {
  if (confirmPassword.value !== password.value) {
    confirmPassword.setCustomValidity("Passwords do not match.");
  } else {
    confirmPassword.setCustomValidity("");
  }
});

While the two values differ, the confirm field reports itself as invalid with your message; the moment they match, the custom error is cleared. Passing an empty string always means "no problem".

8. Your first JavaScript validation script

Now build the manual pattern from scratch, because it is the foundation of every realistic example that follows. Start with one required field:

<form id="signup">
  <label for="name">Your name</label>
  <input id="name" type="text">
  <p id="name-error" class="error"></p>
  <button type="submit">Sign up</button>
</form>
const form = document.querySelector("#signup");
const nameInput = document.querySelector("#name");
const nameError = document.querySelector("#name-error");

form.addEventListener("submit", function (event) {
  event.preventDefault();

  if (nameInput.value.trim() === "") {
    nameError.textContent = "Please enter your name.";
    nameInput.focus();
    return;
  }

  nameError.textContent = "";
  alert("Welcome, " + nameInput.value.trim() + "!");
});

Read the listener as five small decisions:

  • event.preventDefault() stops the page from reloading, so our messages survive.
  • value.trim() removes spaces, so a field containing only spaces counts as empty.
  • The if check finds the failure first and returns early — this "guard clause" style keeps nesting shallow.
  • textContent writes the message safely into the paragraph; it never interprets anything as HTML.
  • focus() moves the cursor to the broken field so the user can fix it immediately.

9. Worked example: required fields and email format

The most common real-world rule after "not empty" is "must look like an email". Browsers do this with type="email", but when you build the messages yourself you need the same check in JavaScript, and that means a regular expression:

const form = document.querySelector("#contact-form");
const emailInput = document.querySelector("#email");
const emailError = document.querySelector("#email-error");

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

form.addEventListener("submit", function (event) {
  event.preventDefault();

  const value = emailInput.value.trim();

  if (value === "") {
    emailError.textContent = "Email is required.";
    emailInput.focus();
    return;
  }

  if (!emailPattern.test(value)) {
    emailError.textContent = "Please enter a valid email address.";
    emailInput.focus();
    return;
  }

  emailError.textContent = "";
  alert("Subscribed with " + value);
});

With input [email protected] the form is accepted; with ravi@gmail the message Please enter a valid email address. appears under the field.

How the pattern reads, piece by piece:

  • /…/ — the delimiters that mark a regular expression in JavaScript.
  • ^ and $ — the whole value must match from start to end, not just part of it.
  • [^\s@] — any character that is not whitespace and not an @.
  • + — one or more of the previous item.
  • \. — a real dot (a plain . in regex means "any character", so it is escaped).

So the pattern demands something, then @, then something, then a dot, then something. It is deliberately simple: enough to catch honest typos, without trying to be a complete email standard.

10. Worked example: password and confirmation

The "two fields must match" rule cannot be written as an HTML attribute, because it compares two fields. This is exactly where JavaScript earns its keep:

const form = document.querySelector("#password-form");
const password = document.querySelector("#password");
const confirmPassword = document.querySelector("#confirm");
const passwordError = document.querySelector("#password-error");
const confirmError = document.querySelector("#confirm-error");

form.addEventListener("submit", function (event) {
  event.preventDefault();

  passwordError.textContent = "";
  confirmError.textContent = "";

  if (password.value.length < 8) {
    passwordError.textContent = "Password must be at least 8 characters.";
    password.focus();
    return;
  }

  if (password.value !== confirmPassword.value) {
    confirmError.textContent = "Passwords do not match.";
    confirmPassword.focus();
    return;
  }

  alert("Password looks good!");
});

Two habits in this example are worth copying everywhere:

  • Clear all old messages first. Otherwise last attempt's errors linger next to this attempt's success.
  • One error per field, in order. Length is checked before matching, so the user fixes problems in the order they appear on screen.

11. Regular expressions for custom patterns

Once you can read one regex, a whole family of rules opens up. The workhorse method is pattern.test(value), which returns true or false:

RulePatternMeaning
10-digit mobile number/^[6-9][0-9]{9}$/starts with 6–9, then exactly 9 more digits
6-digit pincode/^[1-9][0-9]{5}$/first digit 1–9, then exactly 5 more digits
Username/^[a-zA-Z0-9_]{3,16}$/letters, digits or underscore, 3 to 16 characters
Letters and spaces only/^[A-Za-z ]+$/useful for names
Email (simple)/^[^\s@]+@[^\s@]+\.[^\s@]+$/the pattern from the earlier example

New symbols used here: \d means any digit, {9} means "exactly 9 times", {3,16} means "between 3 and 16 times", and [6-9] is a character class allowing one character from that range.

A rule of thumb keeps your regexes healthy: validate the shape, not the person. Phone number and pincode patterns are fine, but patterns that try to validate full names or international addresses reject real people — names with hyphens, apostrophes or non-English letters. When in doubt, check only for emptiness and outrageous length, and let the rest be free.

12. Worked example: a complete signup form with inline errors

Everything now comes together in one realistic form: several fields, one rule set, inline messages under each field, checked on submit and kept up to date while the user types. First the markup:

<form id="signup-form" novalidate>
  <label for="fullname">Full name</label>
  <input id="fullname" type="text">
  <p class="error" data-error-for="fullname"></p>

  <label for="email">Email</label>
  <input id="email" type="email">
  <p class="error" data-error-for="email"></p>

  <label for="password">Password</label>
  <input id="password" type="password">
  <p class="error" data-error-for="password"></p>

  <button type="submit">Create account</button>
</form>

Note the novalidate attribute: it switches off the browser's automatic bubbles so that our own inline messages are the single source of feedback. Only do this when your JavaScript truly replaces the built-in checks. Each error paragraph is found by a data-error-for attribute that names its field, which keeps the pairing in one place. Now the script:

const form = document.querySelector("#signup-form");

const rules = {
  fullname: function (value) {
    if (value.trim() === "") return "Full name is required.";
    if (value.trim().length < 3) return "Name must be at least 3 characters.";
    return "";
  },
  email: function (value) {
    if (value.trim() === "") return "Email is required.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim())) {
      return "Enter a valid email like [email protected].";
    }
    return "";
  },
  password: function (value) {
    if (value === "") return "Password is required.";
    if (value.length < 8) return "Password must be at least 8 characters.";
    return "";
  }
};

function showError(id, message) {
  const box = document.querySelector('[data-error-for="' + id + '"]');
  box.textContent = message;
}

function validateField(id) {
  const input = document.querySelector("#" + id);
  const message = rules[id](input.value);
  showError(id, message);
  return message === "";
}

form.addEventListener("submit", function (event) {
  event.preventDefault();

  let allValid = true;
  const ids = Object.keys(rules);
  for (const id of ids) {
    if (!validateField(id)) {
      allValid = false;
    }
  }

  if (allValid) {
    alert("All fields are valid. Ready to send to the server!");
  }
});

["fullname", "email", "password"].forEach(function (id) {
  const input = document.querySelector("#" + id);
  input.addEventListener("blur", function () {
    validateField(id);
  });
  input.addEventListener("input", function () {
    showError(id, "");
  });
});

The design decisions matter more than the lines themselves:

  • Rules live in one object. Each field maps to a function that returns an error string or an empty string. Adding a field means adding one entry, not rewriting the listener.
  • validateField() is reusable. The same function runs on submit and when a field loses focus (blur), so the user meets the same rules at both moments.
  • Errors clear while typing. The input event wipes the message as soon as the user starts fixing the field, so the interface never argues with them.
  • One success path. Only when every rule returns an empty string does the flow continue — the point where a real application would call fetch() to post the data.

13. Accessible error messages and common mistakes

An error message that a user cannot perceive is not a message. Screen readers announce changes in properly marked regions, so connect each error to its field and mark the region as live:

<label for="email">Email</label>
<input id="email" type="email" aria-describedby="email-error">
<p id="email-error" aria-live="polite"></p>

aria-describedby tells assistive technology that email-error describes this field; aria-live="polite" makes text placed there announce itself without interrupting the user. A red border alone helps nobody who cannot see it.

Finally, the mistakes that appear in almost every beginner project — recognising them is half the fix:

  • Validating only in the browser. Client-side checks can be bypassed; the server must repeat every rule.
  • Forgetting preventDefault() — the page reloads, the errors vanish, and the user loses their typing.
  • Adding novalidate without replacement. Switching off the browser's checks while writing none of your own means nothing is validated.
  • Scolding on every keystroke. Flagging "invalid" mid-typing feels hostile; validate on blur and on submit, and clear errors on input.
  • Skipping trim(), so a field of spaces passes an emptiness test.
  • Building messages with innerHTML, which would run any markup the user typed. textContent is always the safe choice for user-related text.
  • Colour as the only signal. A red border without a text message fails users with colour blindness and screen readers alike.

14. Validating selects, checkboxes and radio groups

Text fields are only part of a real form. Dropdowns, tick boxes and radio buttons are validated differently, because the value you read from them has a different shape:

  • A select reports its value as the value of the chosen option. Adding a first option with value="" as a placeholder gives you a simple emptiness test.
  • A checkbox reports a checked boolean, not a string. The rule is usually just "must be true".
  • A radio group is many inputs sharing one name. Each radio is a separate element, so the group's answer is found by asking which one is :checked.
<label for="city">City</label>
<select id="city">
  <option value="">Select a city</option>
  <option value="pune">Pune</option>
  <option value="mumbai">Mumbai</option>
</select>
const city = document.querySelector("#city");
const terms = document.querySelector("#terms");

if (city.value === "") {
  // nothing selected yet
}

if (!terms.checked) {
  // box is not ticked
}

const selected = document.querySelector('input[name="batch"]:checked');
const batch = selected ? selected.value : "";

The last line is the pattern to memorise: :checked finds the radio the user picked, and the ternary handles the case where nothing is picked at all.

15. Advanced example: validating a date of birth by age

Some rules cannot be written as a static HTML attribute because they depend on today's date. "Must be at least 18 years old" is one of them — the valid dates change every day. With type="date" the browser gives the value as a YYYY-MM-DD string, which new Date() can turn into a real date object:

const dobInput = document.querySelector("#dob");
const dobError = document.querySelector("#dob-error");

function calculateAge(dob, today) {
  let age = today.getFullYear() - dob.getFullYear();
  const beforeBirthday =
    today.getMonth() < dob.getMonth() ||
    (today.getMonth() === dob.getMonth() && today.getDate() < dob.getDate());
  if (beforeBirthday) {
    age--;
  }
  return age;
}

dobInput.addEventListener("change", function () {
  dobError.textContent = "";

  if (dobInput.value === "") {
    dobError.textContent = "Date of birth is required.";
    return;
  }

  const dob = new Date(dobInput.value);
  const today = new Date();

  if (dob > today) {
    dobError.textContent = "Date of birth cannot be in the future.";
    return;
  }

  if (calculateAge(dob, today) < 18) {
    dobError.textContent = "You must be at least 18 years old to register.";
  }
});

The age calculation subtracts the birth year from the current year, then subtracts one more if this year's birthday has not happened yet. Two checks guard the input: a future date is rejected first, and only then is the age rule applied.

16. Live validation with debouncing

The input event fires on every keystroke. Running a validation function on each keystroke has two problems: it is wasted work, and it shouts "invalid email!" while the user is still typing the @. Debouncing means: wait until the user pauses, and only then run the check.

const emailInput = document.querySelector("#email");
let timer;

emailInput.addEventListener("input", function () {
  clearTimeout(timer);
  timer = setTimeout(function () {
    validateField("email");
  }, 400);
});

Reading the handler:

  • Each keystroke calls clearTimeout(timer), cancelling the check that the previous keystroke scheduled.
  • Then it schedules a new check 400 milliseconds in the future.
  • Only when the user stops typing for 400 ms does validateField("email") actually run.

Debouncing is a general JavaScript technique, not a form trick — the identical pattern powers search boxes that wait for a pause before calling the server.

17. Choosing when to validate: a timing strategy

You now have every moment of validation available. Real forms combine them deliberately:

MomentWhat it is good forWatch out for
On submit onlyOne full check before anything is sent; the smallest amount of codeThe user learns about all errors at the end
On blurA per-field verdict at a natural pause, when the user leaves a fieldTabbing through empty required fields shows errors aggressively
On input, after an errorRe-checking only fields already marked invalid, so the message clears the instant the fix landsNoisy if applied before any error exists
On input, debouncedLive feedback for slow or talkative checksNeeds timer management; never flag "invalid" mid-word
The combination used most often in production forms: validate each field on blur, re-validate it on input once it has an error, and always run every rule on submit. The signup example earlier in this module follows exactly this shape.

18. Common mistakes and the correct way

Part 1 listed the beginner errors around messaging and accessibility. Here are the traps that appear once your forms grow past plain text fields — each with its fix:

MistakeWhat goes wrongCorrect way
Reading a radio group with radio.valueYou get that one radio's fixed value even when it is unselectedQuery with input[name="x"]:checked and handle the null case
Treating a type="number" value as a numbervalue is always a string, so + joins and comparisons misbehaveConvert with Number(value) and test with Number.isNaN()
Omitting type on helper buttons inside a formA button without a type defaults to submit and fires your validationWrite type="button" on every non-submit button
Calling setCustomValidity() without clearing itThe field stays invalid forever, even after the fixAlways pass "" when the rule passes
Reporting every error with alert()Blocks the page, one message at a time, no contextInline messages next to the fields
Using a placeholder as the labelIt vanishes on typing and is skipped by many screen readersA real <label> connected with for and id
Clearing messages only on the next submitFixed fields still show last attempt's errorsClear on input or change
Comparing or storing emails with mixed case[email protected] and [email protected] look like two different peopleNormalise with value.trim().toLowerCase() before comparing or saving

The radio mistake is common enough to deserve a before-and-after:

// wrong: always "morning", checked or not
const batch = document.querySelector("#morning").value;

// right: read whichever radio is actually selected
const checked = document.querySelector('input[name="batch"]:checked');
const batch = checked ? checked.value : "";

19. Best practices for form validation

  • Keep every rule in one place. A map of field-to-function, like the one in the project below, means one new entry per field — never a copy-pasted if chain in several listeners.
  • Use the correct input type. type="email", type="tel", type="date" and type="number" each give you a free constraint plus the right mobile keyboard.
  • Make messages specific and actionable. "Password must be at least 8 characters" tells the user exactly what to do; "Invalid input" tells them nothing.
  • Never lose the user's typing. Cancel the default submission with preventDefault() so a failed validation leaves the form exactly as the user left it.
  • Move focus to the first broken field. Keyboard users must be able to start fixing immediately without hunting for the error.
  • Trim and normalise before testing. Spaces are invisible, and case matters when comparing values later.
  • Test with an empty form and keyboard only. Submit an untouched form on purpose, then Tab through every field — this is how the most patient and the least patient users will meet your form.
  • Keep client-side checks as comfort, not protection. The server repeats every rule, because browser validation is optional for the person sending the request.

20. Practical project: student course registration form

This project builds a complete, runnable registration form — text, email, phone, a dropdown and a terms checkbox — using every pattern from both parts of this page. Follow the steps in order.

Step 1: write the markup with error slots

<form id="registration" novalidate>
  <label for="student">Full name</label>
  <input id="student" type="text">
  <p class="error" data-error-for="student"></p>

  <label for="email">Email</label>
  <input id="email" type="email">
  <p class="error" data-error-for="email"></p>

  <label for="phone">Mobile number</label>
  <input id="phone" type="tel" inputmode="numeric">
  <p class="error" data-error-for="phone"></p>

  <label for="course">Course</label>
  <select id="course">
    <option value="">Choose a course</option>
    <option value="react">React JS Training</option>
    <option value="web">Web Foundations</option>
  </select>
  <p class="error" data-error-for="course"></p>

  <label>
    <input id="terms" type="checkbox">
    I accept the terms and conditions
  </label>
  <p class="error" data-error-for="terms"></p>

  <button type="submit">Register</button>
</form>

Step 2: add the error styles

.error {
  color: crimson;
  font-size: 0.85rem;
  min-height: 1em;
  margin: 0.25rem 0;
}

.invalid {
  border: 2px solid crimson;
}

Step 3: write the rules, the checker and the event wiring

const form = document.querySelector("#registration");

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const phonePattern = /^[6-9][0-9]{9}$/;

const rules = {
  student: function (value) {
    if (value.trim() === "") return "Full name is required.";
    if (value.trim().length < 3) return "Name must be at least 3 characters.";
    return "";
  },
  email: function (value) {
    if (value.trim() === "") return "Email is required.";
    if (!emailPattern.test(value.trim())) return "Enter a valid email address.";
    return "";
  },
  phone: function (value) {
    if (value.trim() === "") return "Mobile number is required.";
    if (!phonePattern.test(value.trim())) {
      return "Enter a 10-digit mobile number starting with 6-9.";
    }
    return "";
  },
  course: function (value) {
    return value === "" ? "Please choose a course." : "";
  },
  terms: function (checked) {
    return checked ? "" : "You must accept the terms to register.";
  }
};

function validateField(id) {
  const field = document.querySelector("#" + id);
  const input = field.type === "checkbox" ? field.checked : field.value;
  const message = rules[id](input);

  document.querySelector('[data-error-for="' + id + '"]').textContent = message;
  field.classList.toggle("invalid", message !== "");
  return message === "";
}

form.addEventListener("submit", function (event) {
  event.preventDefault();

  let allValid = true;
  let firstInvalid = null;

  for (const id of Object.keys(rules)) {
    if (!validateField(id)) {
      allValid = false;
      if (!firstInvalid) {
        firstInvalid = document.querySelector("#" + id);
      }
    }
  }

  if (allValid) {
    const name = document.querySelector("#student").value.trim();
    const course = document.querySelector("#course").value;
    alert("Registered " + name + " for " + course + ".");
    form.reset();
  } else {
    firstInvalid.focus();
  }
});

Object.keys(rules).forEach(function (id) {
  const field = document.querySelector("#" + id);

  field.addEventListener("blur", function () {
    validateField(id);
  });

  const recheck = function () {
    if (field.classList.contains("invalid")) {
      validateField(id);
    }
  };
  field.addEventListener("input", recheck);
  field.addEventListener("change", recheck);
});

Step 4: test it like a user

  1. Click Register on the untouched form — every field shows its message, and focus lands on the name field.
  2. Fix the fields one by one — each red border and message clears the moment the value becomes valid, because the re-check only runs on fields already marked invalid.
  3. Tick the terms box and submit — the success alert shows the collected values and form.reset() clears the form.

Notice how much of the script is configuration rather than logic: adding a pincode field tomorrow means one entry in rules, one input and one error paragraph in the markup. Nothing else changes.


21. Practice Exercises

  1. Confirm the password. Add a confirm-password field to the project above. Solve it twice: once with setCustomValidity() as shown earlier in the module, and once with a function in the rules map that compares the two values. Compare which solution gives better error messages.
  2. Add a pincode field. Validate it with the 6-digit pattern from the regex table in part 1, and make sure a pincode starting with 0 is rejected.
  3. Add the age rule. Attach a date-of-birth field using the calculateAge() example, and confirm that a future date is refused before the age is even computed.
  4. Live character counter. Add a "message" textarea with maxlength="200" and a small counter paragraph that shows "137 / 200 characters" updating on every input event, turning red at 200.
  5. Error summary box. On submit, collect every current message and render them as a list at the top of the form, so users of screen readers get one overview instead of hunting per field.
  6. Keyboard-only audit. Unplug the mouse (metaphorically): Tab through the whole form, verify every error is announced or visible, and fix any field whose message never reaches the keyboard user.

22. Interview Questions and Answers

What is client-side form validation and why is it not enough on its own?

It is the checking of form values in the browser, before data is sent anywhere, using HTML constraints, CSS and JavaScript. It gives instant feedback, but it runs on the user's machine and can be bypassed by disabling JavaScript or by sending requests directly to the server. That is why every rule is enforced again server-side, which is the only check that cannot be skipped.

What does event.preventDefault() do inside a submit listener?

It cancels the browser's default action for that event — for a form, the automatic submission and page reload. This lets your code inspect the values and show inline errors first. Without it, the page reloads, the user's typing is lost and the messages never appear.

What is the Constraint Validation API?

It is the built-in system behind HTML form validation. Each form element carries a validity object (a ValidityState) with boolean properties such as valueMissing, typeMismatch, patternMismatch, tooShort and rangeOverflow, plus the methods checkValidity(), reportValidity() and setCustomValidity(), and a validationMessage string describing the first failing rule.

What is the difference between checkValidity() and reportValidity()?

checkValidity() silently returns true or false — useful when you want to render your own messages. reportValidity() performs the same check but also shows the browser's own warning bubble on the first invalid field, which is useful when you want the built-in interface.

How do you validate that two fields match, such as password and confirm password?

No HTML attribute can compare two fields, so JavaScript does it. The cleanest hook is setCustomValidity(): compare the values on input, set your message while they differ, and pass an empty string the moment they match. Alternatively, keep the rule in your validation map and compare the values on submit.

How do you read the selected value of a radio group?

Radio buttons in a group share one name but are separate elements, so you query the selected one: document.querySelector('input[name="batch"]:checked'). This returns null when nothing is selected, which your code must handle. Reading .value from one radio directly just returns that radio's fixed value.

Why is textContent preferred over innerHTML for error messages?

innerHTML parses whatever you give it as HTML, so text containing markup — including text the user typed — would be executed rather than displayed. That is a classic injection (XSS) hole. textContent inserts the string as plain text, so it is always the safe choice for anything built from user input.

What do the :valid and :invalid pseudo-classes do, and what is their pitfall?

They are CSS pseudo-classes that reflect the constraint state of a field, letting you style fields green or red without JavaScript. The pitfall: an empty required field is already invalid, so styling input:invalid directly paints the whole form red on page load. The usual fix is to add a class with JavaScript when the user has actually touched the field, and style only that class.

Which events matter for validation feedback, and when do you use each?

submit runs the full rule set before anything is sent. blur validates a single field when the user leaves it — a natural moment for feedback. input and change re-check or clear errors while the user edits, typically only for fields already marked invalid, so the message disappears the instant the fix lands.

What is debouncing and where does it help in validation?

Debouncing delays an action until a burst of events has stopped. In a form, the input event fires per keystroke, so instead of validating on each one you reset a timer and validate only after the user pauses — commonly a few hundred milliseconds. It avoids flagging errors mid-word and prevents wasted work, and the same technique powers search-as-you-type boxes.

What does the novalidate attribute do, and when should you use it?

Placed on the <form> tag, novalidate switches off the browser's automatic blocking and warning bubbles on submit. You use it when your JavaScript fully replaces the built-in feedback with custom inline messages, so there is exactly one source of validation feedback. Using it without writing that JavaScript means nothing is validated at all.

How would you enforce a minimum age from a date of birth?

A type="date" input gives the value as YYYY-MM-DD, which new Date() parses. First reject a future date, then compute the age: subtract the birth year from the current year and subtract one more if this year's birthday has not yet passed. Because the rule depends on today's date, it cannot be expressed as a static min attribute — it needs JavaScript.


23. Quick Revision Checklist

  • Validation = rules + timing + messaging; all three are your design decisions.
  • preventDefault() in a submit listener stops the reload and preserves the user's typing.
  • field.validity exposes valueMissing, typeMismatch, patternMismatch, tooShort, rangeOverflow and friends.
  • checkValidity() asks quietly; reportValidity() also shows the browser's bubbles.
  • setCustomValidity(message) adds a cross-field rule; setCustomValidity("") clears it.
  • Select: test value === "" against a placeholder option. Checkbox: test .checked.
  • Radio group: read querySelector('input[name="x"]:checked') and handle null.
  • trim() before emptiness checks; Number() before numeric checks; toLowerCase() before email comparisons.
  • textContent for every message — never innerHTML with user input.
  • Recommended timing: validate on blur, re-check on input after an error, always on submit.
  • Debounce keystroke-driven checks instead of validating every keypress.
  • novalidate only when JavaScript fully replaces the built-in checks; every non-submit button gets type="button".
  • Client-side validation is for comfort; the server repeats every rule for safety.

24. Official Documentation and Further Reading

None of the resources gathered for this course cover vanilla form validation directly, so this section points forward instead: both links below continue exactly where this page's final sections lead — building things to practise, and preparing for interviews.

  • 50 React Interview Coding Challenges — the course research highlights this as the standard answer to "What should I build to practice?": a long list of coding challenges and portfolio projects, the natural next step after the registration form you built on this page.
  • Frontend Interview Questions 2026: React, JS & CSS — JavaScript and CSS questions alongside React ones; the research notes that interviews cross-question from basics to advanced and include "traps inside the simple-looking ones", very much like the radio-group and number-input traps listed above.

Conclusion

Form validation is where the DOM module stops being a collection of separate tools and becomes a small, complete product feature: rules written once in a map, feedback delivered inline at the right moments, focus handed to the field that needs fixing, and success handled only when every rule passes. The patterns you built here — the rules object, the reusable validateField(), the blur-input-submit timing, debouncing and accessible messages — are not throwaway classroom code; they are the mental model of every form you will ever ship. Later in this course, React will replace the direct DOM reads with state and controlled components, but the rules, the timing and the wording of your messages will stay exactly as you designed them here.

Learn more in the React JS Training course, or register for a course demo.

Previous Next
whatsapp