Login Form Validation Using HTML, CSS and JS (with Error Message)

Beginner 26 views Oct 12, 2026

Almost every site with accounts has a login form validation, and a good one checks the input before anything is sent to the server: does the email look like an email, and is the password filled in and long enough? In this tutorial you will build a Login Form with Validation that shows a clear message under each field, marks fields in red or green, keeps the button disabled while the form is invalid, and shows a loading state when you submit.

Client-side validation makes forms friendlier, but it never replaces validation on the server. We explain this at the end.

What You'll Learn

By the end of this tutorial you will know:

  • How to validate an email with a regular expression
  • How to show an error message under a field
  • How to validate on input and on blur
  • How to prevent the default form submission
  • How to disable and enable the submit button
  • How to use aria-invalid, aria-describedby and aria-live

Features of This Login Form Validation

  • Email format check
  • Password minimum length of 8
  • Errors appear only after the field has been touched
  • Red and green field borders
  • Submit button enabled only for a valid form
  • Loading state and success message
  • Accessible error messages

Prerequisites

You only need the basics: how to write a simple HTML page, a few CSS rules, and what a JavaScript variable and function are. Along with that, have a code editor such as Visual Studio Code and any modern browser ready. No frameworks, no build tools and no installs.

Project Structure

Create a new folder called login-form-validation and add three empty files inside it:

PLAINTEXT
login-form-validation/
├── index.html   → the page structure
├── style.css    → the look and layout
└── script.js    → the behaviour

Step 1: Create the HTML Structure

Create index.html. A form with two fields, each followed by an empty error paragraph, and a submit button that starts out disabled.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login Form Validation</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <main class="card">
    <h1>Welcome back</h1>
    <p class="sub">Sign in to continue</p>

    <form id="form" novalidate>
      <div class="field">
        <label for="email">Email</label>
        <input type="email" id="email" autocomplete="email" aria-describedby="emailErr">
        <p class="err" id="emailErr" aria-live="polite"></p>
      </div>

      <div class="field">
        <label for="password">Password</label>
        <input type="password" id="password" autocomplete="current-password" aria-describedby="passwordErr">
        <p class="err" id="passwordErr" aria-live="polite"></p>
      </div>

      <button type="submit" id="submit" disabled>Sign in</button>
      <p id="result" class="result" role="status"></p>
    </form>
  </main>

  <script src="script.js"></script>
</body>
</html>

Step 2: Add the CSS Styling

Create style.css. JavaScript adds an invalid or valid class to each input. The error text is red and takes up space even when empty, so the layout does not jump when a message appears.

CSS
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: "Segoe UI", Arial, sans-serif;
  background: #eef1f8;
  color: #1f2937;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.card {
  width: 100%;
  max-width: 420px;
  background: #fff;
  padding: 28px;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(31, 41, 55, 0.12);
}

h1 {
  font-size: 1.5rem;
  text-align: center;
  margin-bottom: 18px;
}

.sub {
  text-align: center;
  color: #6b7280;
  margin: -8px 0 20px;
}

.field {
  margin-bottom: 16px;
}

label {
  display: block;
  font-size: 0.9rem;
  font-weight: 600;
  color: #4b5563;
  margin-bottom: 6px;
}

input {
  width: 100%;
  padding: 12px;
  font-size: 1rem;
  border: 2px solid #e5e7eb;
  border-radius: 10px;
  transition: border-color 0.2s;
}

input:focus {
  outline: none;
  border-color: #4f46e5;
}

input.valid {
  border-color: #16a34a;
}

input.invalid {
  border-color: #dc2626;
}

.err {
  color: #dc2626;
  font-size: 0.85rem;
  min-height: 1.2em;
  margin-top: 4px;
}

button[type="submit"] {
  width: 100%;
  padding: 13px;
  border: none;
  border-radius: 10px;
  background: #4f46e5;
  color: #fff;
  font-size: 1rem;
  font-weight: 700;
  cursor: pointer;
}

button[type="submit"]:hover:not(:disabled) {
  opacity: 0.92;
}

button[type="submit"]:disabled {
  background: #a5b4fc;
  cursor: not-allowed;
}

.result {
  text-align: center;
  margin-top: 14px;
  font-weight: 600;
  color: #16a34a;
  min-height: 1.4em;
}

Step 3: Add the JavaScript

Create script.js. Each field has a small check function that returns an error message, or an empty string if the value is fine. One function shows the message and colours the field, and another updates the button.

JAVASCRIPT
const form = document.getElementById('form');
const email = document.getElementById('email');
const password = document.getElementById('password');
const submit = document.getElementById('submit');
const result = document.getElementById('result');

const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

// each check returns an error message or an empty string
const checks = {
  email(value) {
    value = value.trim();
    if (!value) return 'Please enter your email.';
    if (!EMAIL_PATTERN.test(value)) return 'That does not look like a valid email.';
    return '';
  },
  password(value) {
    // passwords are not trimmed: spaces can be part of a real password
    if (!value) return 'Please enter your password.';
    if (value.length < 8) return 'Password must be at least 8 characters.';
    return '';
  }
};

const touched = { email: false, password: false };

function validateField(input, show) {
  const message = checks[input.id](input.value);

  if (show) {
    document.getElementById(input.id + 'Err').textContent = message;
    input.classList.toggle('invalid', !!message);
    input.classList.toggle('valid', !message);
    input.setAttribute('aria-invalid', String(!!message));
  }
  return !message;
}

function refreshButton() {
  const ok = validateField(email, false) && validateField(password, false);
  submit.disabled = !ok;
}

[email, password].forEach(input => {
  // 'input' covers typing and most autofill; 'change' catches the rest
  ['input', 'change'].forEach(type => {
    input.addEventListener(type, () => {
      // once a field has been touched, validate while typing
      validateField(input, touched[input.id]);
      refreshButton();
    });
  });
  input.addEventListener('blur', () => {
    touched[input.id] = true;
    validateField(input, true);
  });
});

form.addEventListener('submit', e => {
  e.preventDefault();
  if (submit.disabled) return; // ignore a second submit while "signing in"

  touched.email = touched.password = true;
  const okEmail = validateField(email, true);
  const okPass = validateField(password, true);
  if (!(okEmail && okPass)) return;

  submit.disabled = true;
  submit.textContent = 'Signing in...';
  result.textContent = '';

  // pretend to call a server
  setTimeout(() => {
    submit.textContent = 'Sign in';
    submit.disabled = false;
    result.textContent = 'âś” Signed in as ' + email.value.trim();
  }, 1200);
});

How This Login Form Validation Works

  • novalidate on the form turns off the browser’s own popups, so we can show our own messages.
  • checks is an object with one function per field. Adding a new field means adding a new check and an error paragraph named fieldIdErr.
  • touched remembers whether the user has left the field at least once. Errors are shown only after that, so people are not scolded while still typing their first letter.
  • refreshButton() silently checks both fields (without showing messages) to enable or disable the button.
  • Regular expression: anything that is not a space or @, then @, then more text, a dot and at least two characters. It is simple on purpose; the server will do the real check.
  • aria-invalid, aria-describedby and aria-live let screen readers announce the error text when the field is focused or when the message changes.
  • The email is trimmed before checking, but the password is not, because spaces can be a real part of a password.

Customization Guide

1. Change the password rule

Edit the password check, for example to require a number: if (!/\d/.test(value)) return 'Add at least one number.';

2. Add a "Remember me" box

Add a checkbox and save the email in localStorage when it is ticked.

Future Enhancements

Once the basic version works, here are some ideas to practise with:

  • Add a show / hide password button
  • Add a “forgot password” link and form
  • Send the data to a real PHP or Node.js login endpoint with fetch
  • Lock the form for 30 seconds after five wrong attempts

Troubleshooting Guide

Valid emails are rejected

Check the regular expression. Very strict patterns reject real addresses. The one used here is deliberately simple.

The button stays disabled

Make sure refreshButton() runs on every input and change event. Some browsers fire only change for autofill, which is why the script listens to both.

Related Mini Projects

Want more practice? Try these beginner projects next:

Conclusion

You built a login form with friendly, live validation. Remember: always validate again on the server. Client-side checks improve the experience, but only the server can be trusted.

Technologies Used

HTML5 CSS3 JavaScript

Live Output

See the project in action below. This is the live preview of the code you just learned.

Output Preview