Assignment Chef icon Assignment Chef
All English tutorials

Programming lesson

Mastering Form Validation in JavaScript: A Step-by-Step Guide with Real-World Examples

Learn how to validate HTML forms using JavaScript with this hands-on tutorial. We'll cover event listeners, preventing default actions, and validating inputs like item name, price, and size. Perfect for CPSC1520 students or anyone building web apps.

JavaScript form validation CPSC1520 assignment form validation tutorial validate form JavaScript event listener submit prevent default JavaScript add remove class JavaScript is-invalid class order form validation web development tutorial JavaScript exercises form validation best practices student coding assignment frontend validation JavaScript for beginners form validation example

Why Form Validation Matters in Modern Web Apps

Form validation is a critical part of any web application. Whether you're building an e-commerce checkout, a survey, or a simple order form, ensuring users enter correct data prevents bugs and improves user experience. In this tutorial, we'll walk through a typical assignment: validating an order form with JavaScript, step by step.

Setting Up the Event Listener

Start by linking your JavaScript file in the HTML. Then, select the form with the class new-order-form and add a submit event listener. Use the event object to call preventDefault() so the page doesn't reload.

const form = document.querySelector('.new-order-form');
form.addEventListener('submit', function(event) {
  event.preventDefault();
  // ... rest of code
});

Accessing Form Elements

Use event.target.elements to get the form fields. Assign them to variables for clarity.

const itemName = event.target.elements['item-name'];
const itemPrice = event.target.elements['item-price'];
const itemSize = event.target.elements['item-size'];

Validating the Item Name

Check if the item name is not empty. If valid, remove the is-invalid class. Otherwise, add it and set a flag to false.

let isFormValid = true;

if (itemName.value.trim() !== '') {
  itemName.classList.remove('is-invalid');
} else {
  itemName.classList.add('is-invalid');
  isFormValid = false;
}

Validating the Price

The price must be non-empty and greater than 5. Use a helper function like isGreaterThanFive if provided.

if (itemPrice.value.trim() !== '' && Number(itemPrice.value) > 5) {
  itemPrice.classList.remove('is-invalid');
} else {
  itemPrice.classList.add('is-invalid');
  isFormValid = false;
}

Validating the Size

Size should not be empty. Apply the same pattern.

if (itemSize.value.trim() !== '') {
  itemSize.classList.remove('is-invalid');
} else {
  itemSize.classList.add('is-invalid');
  isFormValid = false;
}

Submitting Only Valid Forms

If isFormValid is true, call the provided addOrderItem function with the values. Then reset the form fields.

if (isFormValid) {
  addOrderItem(itemName.value, itemPrice.value, itemSize.value);
  itemName.value = '';
  itemPrice.value = '';
  itemSize.value = '';
}

Testing Your Validation

Run through these test cases to ensure everything works:

  • Invalid: Item Name: Burger, Price: (empty), Size: (empty)
  • Invalid: Item Name: (empty), Price: 18, Size: (empty)
  • Invalid: Item Name: pop, Price: 4, Size: small
  • Invalid: Item Name: (empty), Price: (empty), Size: Small
  • Valid: Item Name: pop, Price: 6, Size: small

Real-World Connection: Like Ordering from a Food App

Think of this like adding items to your cart in a food delivery app. If you leave the item name blank or enter a price of $0.50, the app should reject it. This same logic powers countless web forms you use daily.

Common Mistakes to Avoid

  • Forgetting to call preventDefault() – the form will refresh the page.
  • Using == instead of === for strict comparison.
  • Not trimming whitespace – ' ' is not empty.

Next Steps: Pushing to GitHub

Once your code passes all test cases, commit and push to your repository. Use git add ., git commit -m "Add form validation", and git push. Submit the repo link as required.

Conclusion

Form validation is a fundamental skill in JavaScript. By following this structured approach, you can build robust forms that improve data quality and user experience. Keep practicing with different form types, and you'll master the pattern in no time.