agyanadda@gmail.com

JS Form Validation

Working with the Page 1 min read Updated Dec 1, 2026 Topic 28 of 38

Checking form data in the browser gives users instant feedback.

Steps

  1. Listen to the form's submit event
  2. Call e.preventDefault() to stop sending
  3. Read values with input.value.trim()
  4. Check each rule and show messages
  5. If everything is fine, send the form (or the data)

Useful checks

  • Required: value === ''
  • Length: value.length < 3
  • Email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
  • Indian mobile: /^[6-9]\d{9}$/.test(value)

Important

Browser validation is for user experience only. Always validate again on the server (PHP/Laravel), because anyone can bypass JavaScript.

Example

Example — Validate a sign-up form HTML
<style>
  .err { color: crimson; font-size: 13px; display: block; }
  input { display: block; margin-top: 8px; padding: 6px; }
</style>

<form id="signup" novalidate>
  <input id="name" placeholder="Name"><span class="err" id="nameErr"></span>
  <input id="email" placeholder="Email"><span class="err" id="emailErr"></span>
  <input id="mobile" placeholder="Mobile"><span class="err" id="mobileErr"></span>
  <button>Sign up</button>
</form>
<p id="ok" style="color:green"></p>

<script>
  document.getElementById('signup').addEventListener('submit', e => {
    e.preventDefault();
    const val = id => document.getElementById(id).value.trim();
    const show = (id, msg) => document.getElementById(id).textContent = msg;
    let valid = true;

    if (val('name').length < 3) { show('nameErr', 'Name must be at least 3 letters'); valid = false; } else show('nameErr', '');
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val('email'))) { show('emailErr', 'Enter a valid email'); valid = false; } else show('emailErr', '');
    if (!/^[6-9]\d{9}$/.test(val('mobile'))) { show('mobileErr', 'Enter a 10-digit mobile number'); valid = false; } else show('mobileErr', '');

    document.getElementById('ok').textContent = valid ? 'All good! Form can be sent.' : '';
  });
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which event should you listen to for validating a form?

Exercise 2 True / False

JavaScript validation means you do not need server validation.

Exercise 3 Fill in the Blank

Use .___() to remove extra spaces before checking a value.

Frequently Asked Questions

It turns off the browser's built-in validation pop-ups so your own JavaScript messages are shown instead.