Forms | Dataplexa

Forms & Validation

Forms are one of the most common ways users interact with websites. Logging in, signing up, searching, and submitting feedback all rely on forms.

JavaScript helps us validate user input before sending it to a server, improving user experience and data quality.


What Is a Form?

A form is a collection of input elements that allow users to enter and submit data.

JavaScript gives us control over how that data is checked and processed.


Why Validation Matters

Validation ensures that users enter correct and meaningful data.

  • Prevents empty submissions
  • Reduces errors
  • Improves usability
  • Saves server resources

Accessing Form Elements

Form fields can be accessed just like any other DOM element.


let username = document.getElementById("username");
let password = document.getElementById("password");
  

Once selected, you can read the value entered by the user.


Reading Input Values


let nameValue = username.value;
let passwordValue = password.value;
  

The value property holds the user’s input.


Basic Validation Example

Here’s a simple example that checks if fields are empty.


let form = document.getElementById("loginForm");

form.addEventListener("submit", function (event) {
  event.preventDefault();

  if (username.value === "" || password.value === "") {
    alert("Please fill in all fields");
  } else {
    alert("Form submitted successfully");
  }
});
  

This prevents submission until the input is valid.


Real-World Example

Imagine a signup form where users forget to enter an email.

Client-side validation immediately informs them, instead of waiting for a server response.


Common Beginner Mistakes

  • Not preventing default form submission
  • Relying only on client-side validation
  • Displaying unclear error messages

Good validation is clear, simple, and helpful.


Thumb Rules

  • Always validate before submitting
  • Use clear error messages
  • Keep validation logic readable
  • Never trust user input blindly

What Comes Next?

Now that you understand how to work with forms, the next step is storing user data in the browser.

In the next lesson, we will learn about local and session storage.