JavaScript Form Validation


What You'll Learn:

  • Validate input fields with JavaScript
  • Prevent form submission if validation fails
  • Show custom error messages
  • Use regular expressions for email/password checks


Files Structure

form-validation/
├── index.html
├── style.css
└── script.js


HTML: index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Form Validation</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="form-container">
<h2>Sign Up</h2>
<form id="signupForm" novalidate>
<div class="form-group">
<label>Name:</label>
<input type="text" id="name" required />
<small class="error"></small>
</div>

<div class="form-group">
<label>Email:</label>
<input type="email" id="email" required />
<small class="error"></small>
</div>

<div class="form-group">
<label>Password:</label>
<input type="password" id="password" required />
<small class="error"></small>
</div>

<div class="form-group">
<label>Confirm Password:</label>
<input type="password" id="confirmPassword" required />
<small class="error"></small>
</div>

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

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


CSS: style.css

body {
  font-family: Arial, sans-serif;
  background-color: #f2f4f8;
  display: flex;
  justify-content: center;
  padding-top: 50px;
}

.form-container {
  background-color: #fff;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
  max-width: 400px;
  width: 100%;
}

h2 {
  text-align: center;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 6px;
}

input {
  width: 100%;
  padding: 10px;
  border-radius: 6px;
  border: 1px solid #ccc;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.error {
  color: red;
  font-size: 0.85rem;
  display: none;
}


JavaScript: script.js

const form = document.getElementById('signupForm');

form.addEventListener('submit', function (e) {
  e.preventDefault(); // prevent submission
  validateForm();
});

function validateForm() {
  let valid = true;

  const name = document.getElementById('name');
  const email = document.getElementById('email');
  const password = document.getElementById('password');
  const confirmPassword = document.getElementById('confirmPassword');

  clearErrors();

  // Name validation
  if (name.value.trim() === "") {
    setError(name, "Name is required");
    valid = false;
  }

  // Email validation
  if (!validateEmail(email.value)) {
    setError(email, "Enter a valid email");
    valid = false;
  }

  // Password validation
  if (password.value.length < 6) {
    setError(password, "Password must be at least 6 characters");
    valid = false;
  }

  // Confirm Password
  if (password.value !== confirmPassword.value) {
    setError(confirmPassword, "Passwords do not match");
    valid = false;
  }

  if (valid) {
    alert("🎉 Form submitted successfully!");
    form.reset();
  }
}

function setError(element, message) {
  const small = element.nextElementSibling;
  small.innerText = message;
  small.style.display = 'block';
}

function clearErrors() {
  const errors = document.querySelectorAll('.error');
  errors.forEach(err => {
    err.innerText = "";
    err.style.display = 'none';
  });
}

function validateEmail(email) {
  const re = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
  return re.test(String(email).toLowerCase());
}