Ways to implement form validation with JavaScript

I'm currently working on a project for my digital class and I'm facing an issue with my booking form. I have two functions that need to execute when a button is clicked - one function validates the form to ensure all necessary fields are filled out, while the other runs the main loop. Despite looking through various resources online, I haven't been able to figure it out yet.

I attempted adding the validForm function within the main loop so that it runs first before the loop. Then, I tried running just the main loop without the validForm function, but it ran the loop first and then checked for the required forms (I actually need it to check for required forms first and then run the loop). It's proving to be quite challenging for me.

--- condensed code snippet (html) ---

<form id="thisForm" method="post" name="thisForm" onsubmit="validForm()">
<label>First name:</label> <input autocomplete="on" id="firstNameInput" placeholder="John" required="" title="Enter your first name" type="text"><br>
<label>Last name:</label> <input autocomplete="on" id="lastNameInput" placeholder="Smith" required="" title="Enter your last name" type="text"><br>
<label>Age:</label> <input autocomplete="on" id="ageInput" placeholder="18" required="" title="Enter your age" type="number"><br>
<label>Email address:</label> <input autocomplete="on" id="emailInput" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80eaefe8eef3ede9f4e8c0e7ede1e9ecaee3efed">[email protected]</a>" required="" title="Enter your email address" type="email">
<button class="button button1" id="submit" onsubmit="loopForm(form)">Confirm Booking</button>
<button class="button button2" id="reset" onclick="index.html">Reset</button>
</form>

--- condensed javascript logic ---

function validForm() {
  var x = document.forms["myForm"]["numberOfDays"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false;
  }
}

function loopForm(form) { // Function executed upon clicking confirm button to send data to firebase
    alert('Test alert for confirm booking');
    var amountOfDays = numberOfDays.value;
    var insuranceFee = 20;
    var BOOKINGFEE = 50;
    var sum = 0 ;
    var cbResults = ' ';
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].type == 'radio') {
            if (form.elements[i].checked == true) {
                vehicleResult = form.elements[i].value;
                vehicleCost = form.elements[i].dataset.price;
                insuranceCost = Math.round(insuranceFee + vehicleCost * amountOfDays);
                outputDays.innerHTML = amountOfDays; 
                outputTest.innerHTML = insuranceCost; 
                outputVehicle.innerHTML = vehicleResult; 
            }
        }
        if (form.elements[i].type == "checkbox") {
            if (form.elements[i].checked == true) {
                cbResults += form.elements[i].value + ', ';
                sum = sum + parseInt(form.elements[i].dataset.price);
                alert(cbResults + "$" + sum);
                outputExtras.innerHTML = cbResults;
                totalCost = Math.round(insuranceCost + sum + BOOKINGFEE); 
                outputCost.innerHTML = '$' + totalCost;
            }
        }
    }
}

I am anticipating the output to lead to a booking summary page instead of refreshing once the page checks for required fields. Currently, the page refreshes before I get to view the booking summary.

Answer №1

Your validForm function is attempting to access a form (myForm) and an input field (numberOfDays) that do not exist in your HTML code, resulting in an error being thrown.

Instead of

var x = document.forms["myForm"]["numberOfDays"].value;

try using

var form = document.forms["thisForm"]; //will return form

and in your HTML code, provide each input field with a unique name so it can be accessed using the form object.

I have assigned a name to each input field, allowing you to access its value by name. For instance, to access the first name, use form.fName.value.

I have updated both your HTML code and validation function:

function validForm() {
    var form = document.forms["thisForm"]
    var fName = form.fName.value;
    var lName = form.lName.value;
    var age =form.age.value;
    var email = form.email.value;
    if (fName == "") {
        alert("First name must be filled out");
        return false;
    }
    if (lName == "") {
        alert("Last name must be filled out");
        return false;
    }
    if (age == "") {
        alert("Age must be filled out");
        return false;
    }
    if (email == "") {
        alert("Email must be filled out");
        return false;
    };
    
    //call your next function here
    //loopForm(form);
}
<form id="thisForm" method="post" name="thisForm" onsubmit="return validForm()">
      <label>First name:</label>
      <input name="fName" autocomplete="on" id="firstNameInput" placeholder="John"  title="Enter your first name" type="text"><br>

      <label>Last name:</label>
      <input name="lName" autocomplete="on" id="lastNameInput" placeholder="Smith" title="Enter your last name" type="text"><br>

      <label>Age:</label>
      <input name="age" autocomplete="on" id="ageInput" placeholder="18"  title="Enter your age" type="number"><br>

      <label>Email address:</label>
      <input name="email" autocomplete="on" id="emailInput" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e040106001d03071a062e09030f0702400d0103">[email protected]</a>"  title="Enter your email address" type="email">

      <button class="button button1" id="submit" >Confirm Booking</button>

      <button class="button button2" id="reset" onclick="index.html">Reset</button>
</form>

Answer №2

To consolidate your code, create a single function that houses all of your form validation logic. Move your validform code into the loopform function and handle the validation checks within the loop. If the form is not valid, return false as shown in the function below:

function loopForm(form) { 
    var x = document.forms["myForm"]["numberOfDays"].value;
    if (x == "") 
     {
       alert("Name must be filled out");
        return false;
     }
    alert('Test alert for confirm booking');
    var amountOfDays = numberOfDays.value;
    var insuranceFee = 20;
    var BOOKINGFEE = 50;
    var sum = 0 ;
    var cbResults = ' ';
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].type == 'radio') {
            if (form.elements[i].checked == true) {
                vehicleResult = form.elements[i].value;
                vehicleCost = form.elements[i].dataset.price;
                insuranceCost = Math.round(insuranceFee + vehicleCost * amountOfDays);

                outputDays.innerHTML = amountOfDays; 
                outputTest.innerHTML = insuranceCost; 
                outputVehicle.innerHTML = vehicleResult; 
            }
        }
        if (form.elements[i].type == "checkbox") {
            if (form.elements[i].checked == true) {
                cbResults += form.elements[i].value + ', ';
                sum = sum + parseInt(form.elements[i].dataset.price);
                alert(cbResults + "$" + sum);
                outputExtras.innerHTML = cbResults;
                totalCost = Math.round(insuranceCost + sum + BOOKINGFEE); //devired values
                outputCost.innerHTML = '$' + totalCost;
            }
        }
    }

return true;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to access a function from a different controller within an AngularJS Ionic framework application

How can I trigger or call the callkhs function in the LihatKhsController from the KhsController? function KhsController($scope, $rootScope){ $scope.$emit('callkhs', {param:'test'}); } I am attempting to retrieve parameter values ...

Collaborative session sharing between two node applications through Single Sign-On (SSO

I currently have a website created with express and node.js. I need to add a nodebb forum to this website, which is a separate node application. Both the main site and the forum use Facebook login, but users have to log in separately using the same Faceboo ...

Speed up - Handle alias resolution with module federation

Currently import federation from '@originjs/vite-plugin-federation'; import react from '@vitejs/plugin-react-swc'; import dns from 'dns'; import path from 'path'; import { visualizer } from 'rollup-plugin-visual ...

Troubleshooting issue: Looping through array in Node.js with Express, JSON, and Handlebars not functioning correctly with

I'm struggling to grasp the concept of looping through an object in Handlebars and transferring information from one location to another. Here is a sample json file that I am attempting to read from. The file, named "testdata.json", contains: { &qu ...

Encountering an error saying "Cannot read property 'x' of null when using Google Charts LineChart"

When I hover over the legend labels on my Google chart, I keep getting an error message that says "Cannot read property 'x' of null," and I'm not sure why. The data is all in JSON format from an AJAX GET request and does not contain any nul ...

Is it secure to use console.time() in a Node.js environment?

Looking at a small snippet of node.js code, here's what I have: console.time("queryTime"); doAsyncIOBoundThing(function(err, results) { console.timeEnd("queryTime"); // Process the results... }); Running this on my development system gives m ...

Having trouble syncing a controller with AngularJS

Despite numerous attempts, I am still struggling to make a single controller function properly. Lately, I've been working on Angular projects and no matter what I do, my controllers just won't cooperate. In my latest project, everything is withi ...

Disable the submit form in AngularJS when the start date and end date are not valid

I want to ensure that my form submission only occurs if the validation for Start date-End date passes. In my form setup, I have the following elements... <form name="scheduleForm" id="scheduleForm" class="form-vertical" novalidate> <input t ...

Split the array into several arrays based on a specific threshold

I have a graph depicting an array [2,8,12,5,3,...] where the x axis represents seconds. I am looking to divide this array into segments when the y values stay 0 for longer than 2 seconds. For example, in this scenario the array would be split into 3 parts: ...

Update information in a table row and store it in the database using Ajax

Looking for some guidance with ajax and javascript here. I'm not very proficient in this area, so any help would be greatly appreciated. I have a table on my page where data is displayed like this: <table class="table table-bordered"> ...

What is the best way to retrieve an input value and store it as a variable in AngularJS?

Is there a way to properly assign an input value to a variable in AngularJS without errors? Currently, I have a working test version on my page, but it involves using both JavaScript and jQuery alongside AngularJS. I'm looking for a cleaner solution w ...

Tips for transferring variables as arguments in javascript

Currently, I am immersed in a test project aimed at expanding my knowledge of web development. Unexpectedly, I have encountered an issue that has left me puzzled on how to proceed. Within this project, there exists a table consisting of 11 cells. While 9 ...

Using the setTimeout function with asynchronous tasks

I have a situation where I need to introduce a 5000ms delay before firing an asynchronous function. To accomplish this, I attempted to utilize the setTimeout() method. This async function is called within a loop that runs multiple times, and each time it i ...

Fetch JSON information from various servers/domains through ajax requests

I am attempting to retrieve JSON data from a different server/domain. My expectation is that the code below should trigger a success alert, but instead, I am getting an error alert $.ajax({ url: "http://xxxx.com/zzzz", ...

Why won't the click event work in Vue when using v-if or v-show?

Attempting to trigger a click event from a div, but if v-if false is present during component rendering, the click event does not work. Here's the code snippet: export default { name: "ProSelect", data() { return { isActive: false ...

Is it wrong to use <match v-for='match in matches' v-bind:match='match'></match>? Am I allowed to incorporate the match variable from the v-for loop into the v-bind attribute on the

I am attempting to display HTML for each individual match within the matches array. However, I am uncertain if <match v-for='match in matches' v-bind:match='match'></match> is the correct syntax to achieve this. To clarify, ...

Transforming JSON data into an interactive table with HTML

After spending four days searching for a solution, I am still unable to figure out my problem. My goal is to convert a JSON string data retrieved from a URL into a dynamic table using JQuery and JavaScript. To achieve this, I need to load the JSON string ...

My JavaScript functions are not compliant with the HTML5 required tag

I am currently developing input fields using javascript/jQuery, but I am facing an issue with the required attribute not functioning as expected. The form keeps submitting without displaying any message about the unfilled input field. I also use Bootstrap ...

Angular2: Dynamically switch between selected checkboxes in a list

Is there a way to toggle a checked checkbox list in Angular2? I am trying to create a button that, when pressed while the full list is visible, will display only the checked items. Pressing the button again would show the entire list. Here's the Plu ...

Attempting to deploy my initial Google Cloud Function, encountering an error message indicating that Express is not detected

Currently in the process of deploying my first Google Cloud function, the code for which can be found here: https://github.com/rldaulton/GCF-Stripe/blob/master/Charge%20Customer/index.js The code starts with the following line: var app = require('e ...