forms validation

Working with Forms: Collecting and Validating User Input

Forms are the backbone of user interaction on the web. Whether you’re signing up for a newsletter, submitting feedback, or logging into a site, you’re using a form.

In this post, we’ll explore:

  • How to create HTML forms
  • How to access form data with JavaScript
  • How to validate input before submission
  • How to give users feedback

By the end, you’ll be able to build a form that’s both functional and user-friendly.


Step 1: Creating a Basic HTML Form

Here’s a simple form with a name and email field:

<form id="contactForm">
  <label for="name">Name:</label>
  <input type="text" id="name" required>

  <label for="email">Email:</label>
  <input type="email" id="email" required>

  <button type="submit">Submit</button>
</form>

Step 2: Accessing Form Data with JavaScript

You can use JavaScript to grab the values users enter:

const form = document.getElementById("contactForm");

form.addEventListener("submit", function(event) {
  event.preventDefault(); // Prevent page reload

  const name = document.getElementById("name").value;
  const email = document.getElementById("email").value;

  console.log("Name:", name);
  console.log("Email:", email);
});

Step 3: Validating Input

Before submitting data, you should check if the input is valid. Here’s a basic example:

if (name.trim() === "") {
  alert("Please enter your name.");
  return;
}

if (!email.includes("@")) {
  alert("Please enter a valid email address.");
  return;
}

You can also use regular expressions for more advanced validation:

const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;

if (!email.match(emailPattern)) {
  alert("Invalid email format.");
  return;
}

Step 4: Styling the Form with CSS

Make your form visually appealing:

form {
  max-width: 400px;
  margin: auto;
  padding: 20px;
  background: #f2f2f2;
  border-radius: 8px;
}

input {
  display: block;
  width: 100%;
  margin-bottom: 15px;
  padding: 10px;
  font-size: 1em;
}

button {
  background-color: #0057b8;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

Step 5: Try It Yourself

Create a form with:

  • Name
  • Email
  • Message

Use JavaScript to:

  • Prevent empty fields
  • Validate email format
  • Show a success message

Bonus: Add a loading spinner or disable the button during submission.


Final Thoughts

Forms are essential for gathering user input. With JavaScript, you can validate data, prevent errors, and improve user experience. This is a key skill for any web developer.

In the next post, we’ll explore Storing Data with JavaScript; using localStorage and sessionStorage to save user data.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top