Accessing Form Data
Before you can validate a form, you need to get the data from it. The first step is to listen for the form's submit event.
HTML
<form id="user-form"> <label for="username">Username:</label> <input type="text" id="username" name="username"> <button type="submit">Register</button> </form> <div id="feedback"></div>
JavaScript
const form = document.getElementById('user-form');
const feedbackDiv = document.getElementById('feedback');
form.addEventListener('submit', function(event) {
  // 1. Prevent the default browser action (reloading the page)
  event.preventDefault();
  // 2. Access the input's value
  const username = document.getElementById('username').value;
  // 3. Simple validation logic
  if (username.length < 5) {
    feedbackDiv.textContent = 'Username must be at least 5 characters long!';
    feedbackDiv.style.color = 'red';
  } else {
    feedbackDiv.textContent = 'Form submitted successfully!';
    feedbackDiv.style.color = 'green';
    console.log({ username: username });
    // In a real app, you would now send this data to a server.
  }
});
The most important line here is event.preventDefault(). Without it, the browser would try to submit the form traditionally, causing a page refresh and preventing our JavaScript from running.
Client-Side Validation: The "Why"
Why validate on the client (in the browser) instead of just on the server?
- Better User Experience (UX): Users get instant feedback without waiting for a server round-trip.
- Reduced Server Load: You prevent invalid data from ever being sent, saving server resources.
Important: Client-side validation is for UX, not for security. A malicious user can always bypass it. You must always validate on the server as well!
Validation Techniques
1. HTML5 Attributes HTML5 provides built-in validation attributes that are easy to use and require no JavaScript.
HTML
<form> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <label for="password">Password (min 8 chars):</label> <input type="password" id="password" name="password" required minlength="8"> <button type="submit">Submit</button> </form>
- required: The field must be filled out.
- type="email": The value must be in a valid email format.
- minlength="8": The value must have at least 8 characters.
- pattern="[A-Za-z]{3}": The value must match a regular expression.
The browser will automatically show default error messages for these.
2. Custom JavaScript Validation For more complex logic (like checking if two passwords match), you'll need JavaScript. Let's expand our earlier example to provide more dynamic feedback.
HTML
<form id="signup-form"> <label for="pwd">Password:</label> <input type="password" id="pwd" name="pwd"> <span class="error-msg" id="pwd-error"></span> <label for="pwd-confirm">Confirm Password:</label> <input type="password" id="pwd-confirm" name="pwd-confirm"> <span class="error-msg" id="pwd-confirm-error"></span> <button type="submit">Sign Up</button> </form>
JavaScript
document.getElementById('signup-form').addEventListener('submit', function(e) {
  e.preventDefault();
  const pwd = document.getElementById('pwd');
  const pwdConfirm = document.getElementById('pwd-confirm');
  const pwdError = document.getElementById('pwd-error');
  const pwdConfirmError = document.getElementById('pwd-confirm-error');
  // Reset previous errors
  pwdError.textContent = '';
  pwdConfirmError.textContent = '';
  let isValid = true;
  if (pwd.value.length < 8) {
    pwdError.textContent = 'Password must be at least 8 characters.';
    isValid = false;
  }
  if (pwd.value !== pwdConfirm.value) {
    pwdConfirmError.textContent = 'Passwords do not match.';
    isValid = false;
  }
  if (isValid) {
    console.log('Form is valid and ready to be submitted!');
    // this.submit(); // or send with Fetch
  }
});
This approach gives you full control over the validation logic and how error messages are displayed.