DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Form Validation System with JavaScript

Every form on the web needs validation. Without it, your database fills up with empty names, fake emails, and passwords that are one character long. Browser built-in validation helps, but a small JavaScript system gives you control over the messages your users actually see.

What you are building

A signup form that checks each field as the user types, shows a clear error under the field that has a problem, and only submits when everything is valid.

The HTML: one error slot per field

<form id="signup-form" novalidate>
  <label>Email
    <input type="text" id="email" />
    <span class="error" id="email-error"></span>
  </label>
  <label>Password
    <input type="password" id="password" />
    <span class="error" id="password-error"></span>
  </label>
  <button type="submit">Sign up</button>
</form>
Enter fullscreen mode Exit fullscreen mode

The novalidate attribute turns off the browser's own popups, so your messages are the only ones the user sees.

The JavaScript: small validators, one per rule

const validators = {
  email: (value) => {
    if (!value) return 'Email is required.';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return 'Enter a valid email address.';
    return '';
  },
  password: (value) => {
    if (value.length < 8) return 'Password must be at least 8 characters.';
    return '';
  }
};

function validateField(id) {
  const input = document.querySelector('#' + id);
  const error = validators[id](input.value);
  document.querySelector('#' + id + '-error').textContent = error;
  return !error;
}

document.querySelector('#signup-form').addEventListener('submit', (e) => {
  e.preventDefault();
  const ok = ['email', 'password'].every(validateField);
  if (ok) console.log('Form is valid — send it to the server.');
});
Enter fullscreen mode Exit fullscreen mode

Each validator is a tiny function that returns an error message or an empty string. That pattern scales: adding a new field means adding one function, not rewriting the system.

Validate while typing, not just on submit

['email', 'password'].forEach((id) => {
  document.querySelector('#' + id).addEventListener('blur', () => validateField(id));
});
Enter fullscreen mode Exit fullscreen mode

Checking on blur — when the user leaves a field — is the sweet spot. Checking on every keystroke annoys people while they are still typing; checking only on submit makes them fix everything at once.

The one thing to remember

Never trust client-side validation alone. It exists to help honest users, not to stop attackers. Always validate again on the server, because anyone can open developer tools and skip your JavaScript entirely.

Top comments (0)