#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
JavaScript Fundamentals

Form validation

Form validation is checking that what a user typed into a form is complete and sensible before it is sent: a required field is filled, an email looks like an email, a password is long enough, two password fields match. In the browser, validation gives instant feedback so people can fix mistakes quickly. It combines built-in HTML attributes with JavaScript for rules HTML cannot express.

Let HTML do the simple checks

Modern browsers validate many rules on their own, with no script needed:

AttributeRule it enforces
requiredThe field cannot be empty.
type="email", type="url"The value must look like an email address or URL.
minlength, maxlengthText length limits.
min, max, stepNumber and date ranges.
patternThe whole value must match a regular expression.

When the form is submitted, the browser blocks submission and shows a message beside the first invalid field. The CSS pseudo-classes :invalid and :valid, or the newer :user-invalid that waits until the user has interacted, let you style fields accordingly.

Adding custom rules with JavaScript

Some rules need code, such as "confirm password must match password". The Constraint Validation API lets you plug custom messages into the browser's own system, so they appear the same way as built-in ones.

<form id="signup" novalidate>
  <label for="email">Email</label>
  <input id="email" name="email" type="email" required>
  <span class="error" id="email-error"></span>

  <label for="pw">Password</label>
  <input id="pw" name="pw" type="password" required minlength="8">

  <label for="pw2">Confirm password</label>
  <input id="pw2" name="pw2" type="password" required>
  <span class="error" id="pw2-error"></span>

  <button>Create account</button>
</form>

<script>
  const form = document.getElementById('signup');
  const pw = form.elements.pw;
  const pw2 = form.elements.pw2;

  function checkMatch() {
    pw2.setCustomValidity(pw2.value === pw.value ? '' : 'Passwords do not match');
  }
  pw.addEventListener('input', checkMatch);
  pw2.addEventListener('input', checkMatch);

  form.addEventListener('submit', (event) => {
    checkMatch();
    if (!form.checkValidity()) {
      event.preventDefault();
      for (const field of form.elements) {
        const box = document.getElementById(`${field.id}-error`);
        if (box) box.textContent = field.validationMessage;
      }
      form.querySelector(':invalid')?.focus();
    }
  });
</script>

setCustomValidity('') with an empty string marks the field valid again. Any other text marks it invalid and becomes its validationMessage. The novalidate attribute turns off the browser's pop-up bubbles so the script can show messages in its own spans, while the rules themselves still apply.

When to show errors

Timing affects how friendly a form feels. Showing "invalid email" after the first letter is annoying. A common approach is to validate a field when it loses focus (the blur or change event), then re-check on every input once it has been marked wrong, so the message disappears as soon as the user fixes it. Always validate everything again on submit.

Making errors accessible

  • Link each message to its input with aria-describedby so screen readers read it.
  • Set aria-invalid="true" on fields with errors.
  • Do not rely on red colour alone; include text.
  • Move focus to the first invalid field after a failed submit.

The mistake that matters most

Treating browser validation as security. Anyone can turn off JavaScript, edit the HTML in developer tools or send a request directly with a tool like curl, skipping your form entirely. Client-side checks are for user convenience. The server must validate every value again before saving it. A second, smaller mistake is writing over-strict patterns, such as an email regex that rejects valid addresses with a plus sign, or a phone pattern that refuses spaces. Keep rules as loose as the real requirement allows.

Summary of the approach

Start with HTML attributes for required fields, types, lengths and patterns. Add custom rules through setCustomValidity, show messages at sensible moments, make them accessible, and always validate again on the server.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course