Skip to main content

Command Palette

Search for a command to run...

Day 9: Form Handling and Validation in JavaScript

Published
3 min read
Day 9: Form Handling and Validation in JavaScript

Welcome back to our JavaScript series! Today, we'll learn about handling forms and validating user input using JavaScript. Forms are a crucial part of web development as they allow users to submit data. Proper validation ensures that the data collected is accurate and safe.

Handling Forms

Handling forms involves getting the values input by the user and processing them. Let's start by learning how to access form elements and their values.

Accessing Form Elements

You can access form elements using their names or IDs. Here's an example of a simple HTML form:

<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email">
  <input type="submit" value="Submit">
</form>

To access the form elements in JavaScript, you can use document.getElementById or document.forms:

let form = document.getElementById('myForm');
let nameInput = form.elements['name'];
let emailInput = form.elements['email'];

Handling Form Submission

To handle form submission, you need to listen for the submit event and prevent the default form submission behavior. This way, you can validate the form data before it is sent to the server.

let form = document.getElementById('myForm');

form.addEventListener('submit', function(event) {
  event.preventDefault(); // Prevent the form from submitting

  let name = form.elements['name'].value;
  let email = form.elements['email'].value;

  // Perform validation and other actions here

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

Form Validation

Form validation ensures that the user inputs valid data. You can perform validation in JavaScript before submitting the form data. Let's cover some common validation techniques:

Required Fields

Check if the required fields are not empty.

function validateRequiredFields() {
  let name = form.elements['name'].value;
  let email = form.elements['email'].value;

  if (!name || !email) {
    alert('All fields are required.');
    return false;
  }

  return true;
}

Email Validation

Use a regular expression to validate the email format.

function validateEmail(email) {
  let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailPattern.test(email);
}

Combining Validations

Combine multiple validations to ensure all checks are performed.

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

  let name = form.elements['name'].value;
  let email = form.elements['email'].value;

  if (!validateRequiredFields() || !validateEmail(email)) {
    return; // Stop form submission if validation fails
  }

  // Form is valid, proceed with submission or other actions
  console.log('Form submitted successfully!');
});

function validateRequiredFields() {
  let name = form.elements['name'].value;
  let email = form.elements['email'].value;

  if (!name || !email) {
    alert('All fields are required.');
    return false;
  }

  return true;
}

function validateEmail(email) {
  let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailPattern.test(email)) {
    alert('Invalid email format.');
    return false;
  }

  return true;
}

Real-Time Validation

You can also provide real-time validation by listening to the input or change events on form elements.

let nameInput = form.elements['name'];
let emailInput = form.elements['email'];

nameInput.addEventListener('input', function() {
  if (nameInput.value) {
    nameInput.style.borderColor = ''; // Reset border color
  } else {
    nameInput.style.borderColor = 'red'; // Highlight field in red
  }
});

emailInput.addEventListener('input', function() {
  if (validateEmail(emailInput.value)) {
    emailInput.style.borderColor = ''; // Reset border color
  } else {
    emailInput.style.borderColor = 'red'; // Highlight field in red
  }
});

Summary

Today, we learned about handling forms and validating user input using JavaScript. Tomorrow, we'll continue exploring more advanced JavaScript topics.

More from this blog

Mohit's blog

51 posts