Lesson 19 of 30

Form Validation

Validating User Input

Form validation ensures users enter correct and complete information before submitting data to a server.

JavaScript allows you to validate forms on the client-side, providing immediate feedback and preventing invalid submissions.

Proper validation improves user experience and reduces server load by catching errors before data is sent.

Example
// Basic form validation
function validateForm() {
  const name = document.getElementById('name').value;
  const email = document.getElementById('email').value;
  const age = document.getElementById('age').value;

  // Check if fields are empty
  if (name === '' || email === '' || age === '') {
    alert('All fields are required!');
    return false;
  }

  // Validate email format
  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailPattern.test(email)) {
    alert('Please enter a valid email!');
    return false;
  }

  // Validate age is a number
  if (isNaN(age) || age < 1 || age > 120) {
    alert('Please enter a valid age!');
    return false;
  }

  return true; // Form is valid
}

// Attach to form submit
document.getElementById('myForm').addEventListener('submit', function(event) {
  if (!validateForm()) {
    event.preventDefault(); // Stop submission
  }
});
  • Required Fields - Check if fields are not empty
  • Email Validation - Use regex patterns to verify format
  • Number Validation - Check if input is numeric and within range
  • Length Validation - Ensure minimum/maximum character limits
  • Pattern Matching - Use regular expressions for complex validation
  • Real-time Validation - Validate as user types using input events
  • Custom Error Messages - Provide clear, specific feedback
Try Form Validation
HTML
<form id="registrationForm">
  <div class="form-group">
    <label>Username (3-15 characters):</label>
    <input type="text" id="username" placeholder="Enter username">
    <span class="error" id="usernameError"></span>
  </div>

  <div class="form-group">
    <label>Email:</label>
    <input type="text" id="email" placeholder="Enter email">
    <span class="error" id="emailError"></span>
  </div>

  <div class="form-group">
    <label>Password (min 6 characters):</label>
    <input type="password" id="password" placeholder="Enter password">
    <span class="error" id="passwordError"></span>
  </div>

  <div class="form-group">
    <label>Age:</label>
    <input type="number" id="age" placeholder="Enter age">
    <span class="error" id="ageError"></span>
  </div>

  <button type="submit">Register</button>
  <div id="successMessage"></div>
</form>
CSS
.form-group {
  margin: 15px 0;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input {
  width: 100%;
  padding: 10px;
  font-size: 16px;
  border: 2px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

input.invalid {
  border-color: #f44336;
  background-color: #ffebee;
}

input.valid {
  border-color: #4CAF50;
  background-color: #e8f5e9;
}

.error {
  display: block;
  color: #f44336;
  font-size: 14px;
  margin-top: 5px;
  min-height: 20px;
}

button {
  width: 100%;
  padding: 12px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 10px;
}

button:hover {
  background: #1976D2;
}

#successMessage {
  margin-top: 15px;
  padding: 10px;
  background: #4CAF50;
  color: white;
  border-radius: 4px;
  display: none;
}
JavaScript
const form = document.getElementById('registrationForm');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const age = document.getElementById('age');

function showError(input, message) {
  const errorElement = document.getElementById(input.id + 'Error');
  errorElement.textContent = message;
  input.classList.add('invalid');
  input.classList.remove('valid');
}

function showSuccess(input) {
  const errorElement = document.getElementById(input.id + 'Error');
  errorElement.textContent = '';
  input.classList.remove('invalid');
  input.classList.add('valid');
}

function validateUsername() {
  const value = username.value.trim();
  if (value === '') {
    showError(username, 'Username is required');
    return false;
  } else if (value.length < 3 || value.length > 15) {
    showError(username, 'Username must be 3-15 characters');
    return false;
  } else {
    showSuccess(username);
    return true;
  }
}

function validateEmail() {
  const value = email.value.trim();
  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (value === '') {
    showError(email, 'Email is required');
    return false;
  } else if (!emailPattern.test(value)) {
    showError(email, 'Please enter a valid email');
    return false;
  } else {
    showSuccess(email);
    return true;
  }
}

function validatePassword() {
  const value = password.value;
  if (value === '') {
    showError(password, 'Password is required');
    return false;
  } else if (value.length < 6) {
    showError(password, 'Password must be at least 6 characters');
    return false;
  } else {
    showSuccess(password);
    return true;
  }
}

function validateAge() {
  const value = age.value;
  if (value === '') {
    showError(age, 'Age is required');
    return false;
  } else if (isNaN(value) || value < 13 || value > 120) {
    showError(age, 'Please enter a valid age (13-120)');
    return false;
  } else {
    showSuccess(age);
    return true;
  }
}

// Real-time validation
username.addEventListener('blur', validateUsername);
email.addEventListener('blur', validateEmail);
password.addEventListener('blur', validatePassword);
age.addEventListener('blur', validateAge);

// Form submission
form.addEventListener('submit', function(event) {
  event.preventDefault();

  const isUsernameValid = validateUsername();
  const isEmailValid = validateEmail();
  const isPasswordValid = validatePassword();
  const isAgeValid = validateAge();

  if (isUsernameValid && isEmailValid && isPasswordValid && isAgeValid) {
    const successMsg = document.getElementById('successMessage');
    successMsg.textContent = 'Registration successful!';
    successMsg.style.display = 'block';
    form.reset();
    setTimeout(() => {
      successMsg.style.display = 'none';
    }, 3000);
  }
});
Notes
  • Client-Side Only: Always validate on the server too! Client-side validation can be bypassed.
  • User Experience: Show validation errors after user finishes typing (blur event) rather than on every keystroke.
  • Accessibility: Use proper labels, aria attributes, and ensure error messages are announced to screen readers.