I am currently facing an issue with validating forms in JavaScript Document Object Model (DOM)

Whenever I click on a field and move to another one, the span tag turns red. Then, after pressing the submit button, an alert message pops up. However, if I turn the span red, fill in the field, and press the submit button, it shows success even if other fields are left blank.


const regForm = document.getElementById('regForm');
var validObjects = document.querySelectorAll('[customValidate]');
validObjects.forEach(function(element) {
    element.addEventListener('blur', function() {
        var emoji = element.previousElementSibling;
        var label = emoji.previousElementSibling;

        if (!element.value) {
            emoji.className = "far fa-frown float-right  text-danger";
            var span = document.createElement("span");
            span.innerHTML = " * Required";
            span.style.color = "red";
            if (!label.getElementsByTagName("span")[0])
                label.appendChild(span);
            isValid = false;
        } else {
            emoji.className = "far fa-smile float-right  text-success";
            var span = label.getElementsByTagName("span")[0];
            if (span)
                label.removeChild(span);
            isValid = true;
        }
    });
});
regForm.addEventListener('submit', function(event) {
    event.preventDefault();
    var isValid = true;

    validObjects.forEach(function(element) {
        isValid = element.value ? true : false;
    })
    if (!isValid) {
        alert("empty!");
    } else {
        alert("success!");
    }
});

JSFiddle: https://jsfiddle.net/roop06/cjmdabrf/

Answer №1

since the value of isValid will only be determined by the last item in the forEach loop

validObjects.forEach(function(element) {
    isValid = element.value ? true : false; // changes false to true on the final iteration
}) 

If you prefer using forEach but want to retain the previous state of isValid, you can code it like this:

var isValid = true;
validObjects.forEach(function(element) {
    isValid = element.value ? isValid : false;
}) 

Alternatively, if you are only checking for validity without any additional tasks in the loop, a more efficient approach is to use the every method which stops at the first false occurrence.

var isValid = validObjects.every(function (element) {
  return element.value.length
})

var form = document.querySelector('form');
var validObjects = Array.from(document.querySelectorAll('[customValidate]'));
form.addEventListener("submit", function (e) {
  var isValid = validObjects.every(function (element) {
    return element.value.length
  })
  return isValid
})
<form>
  <input customValidate>
  <input customValidate>
  <input customValidate>
  <button>submit</button>
</form>

Alternatively, you can utilize the built-in HTML5 validation feature with required attribute and rely on the browser for validation.

<form>
  <input customValidate required>
  <input customValidate required>
  <input customValidate required>
  <button>submit</button>
</form>

Answer №2

Give this a shot

CodePen

checkObjects.forEach(function(item) {
       if(!(item.input)){
        isCorrect = false;
       }
    })

Answer №3

Your issue arises from the fact that when the last field is valid, the isValid flag remains true indefinitely. To resolve this, you can modify your logic to cease setting the flag once an invalid field has been identified:

validObjects.forEach(function (element) {
    if (isValid) {
        isValid = element.value ? true : false;
    }
});

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

A guide on resolving the TypeError 'download property of undefined' issue when using Puppeteer with browser.downloads.download

Using puppeteer, I am automating the login process to access my account on a content provider's site and download multiple zip files. After obtaining an array of links to download, I go through each link in a loop and utilize the browser.downloads.dow ...

Tips for muting console.log output from a third-party iframe

As I work on developing a web application using NEXT.js, I am encountering an issue with a third party iframe that is generating numerous console logs. I am seeking a way to silence these outputs for the iframe. The code in question simply includes an < ...

Navigating through states in AngularJS

My application has three states: app, app.devices, and app.devices.device. While the first two states are functioning properly, the app.devices.device state is not working as expected. Here is the code for reference: http://pastebin.com/r1kYuExp http://pa ...

Page jumping vertically in Chrome upon reload, with Firefox and Internet Explorer functioning properly

Utilizing this jQuery script, I am able to center a website vertically within the browser window if it exceeds the height of the outer wrapper-div, which has fixed dimensions. $( document ).ready(function() { centerPage(); )}; // center page vertic ...

The callback function in AngularJS filters

I'm currently using an AngularJS filter to sort through a list of items. Here is the Jade markup I am using: li(ng-repeat="parcel in parcels | filter : filterActiveAreaParcels") After the filter function runs and the elements are displayed in the DO ...

Verify that the text entered in the form is accurate, and if it meets the required criteria, proceed to the next

Is it possible to achieve this without using JavaScript? If not, I'd like to find the simplest solution. I have a form that functions similar to a password entry field, and I would like to redirect users to a certain page if they type in a specific p ...

Tips on implementing v-show within a loop

Hey @zero298, there are some key differences in the scenario I'm dealing with. My goal is to display all the items in the object array and dynamically add UI elements based on user input. Additionally, v-if and v-show function differently (as mentione ...

Console displays 'undefined' when using the post method with Node.js/Express

Below is the code for my upload.ejs page: <%- include('header' ,{ title:"Playground" }) -%> <div class="wrapper"> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="text" name="name" place ...

The issue of CSS not being connected properly on Github

I have successfully connected my CSS folder, which includes the styles.css file, to my index.html using the following code: <link rel="stylesheet" href="css/styles.css"> Even though it works fine when I test it locally, the CSS d ...

How can I detect a change in user input using jQuery?

When utilizing jquery .oninput with an element, the event will trigger instantly whenever there is a change in the input value. In my scenario, it is necessary for me to validate the input value by calling the service immediately after any changes occur. ...

What is the correct way to define the onClick event in a React component?

I have been encountering an issue while trying to implement an onClick event in React using tsx. The flexbox and button are being correctly displayed, but I am facing a problem with the onClick event in vscode. I have tried several ideas from the stack com ...

developing a loading animation with progress indicator in CSS3

I have been working on creating a preloader, but I am having trouble embedding the percentage with the CSS circle. So far, I have tried various plugins without success. Can anyone help me with this issue? Here is my current progress. Below is the HTML co ...

Chrome is experiencing a problem with anchor tags that have an href attribute set to a "blob:" URL and using a target of "_blank"

My current project involves developing a website feature that allows users to download a PDF version of a page. To achieve this, the generated HTML is rendered into a PDF on the server, which is then returned as a Base64-encoded PDF. This data is converted ...

I keep running into errors whenever I try to run npm install in my React JS project. The only way for me to successfully install dependencies is by using npm install --force. How can I go about resolving these

I am encountering this error message while working on my project: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @mui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681b1c11040d1b ...

Having trouble retrieving information from Node.js service in AngularJS 2

I am currently expanding my knowledge of Angular and attempting to retrieve data from a node js service using Angular 2 services. When I access the node js services directly from the browser, I can see the results. However, when I attempt to fetch the dat ...

Checking for valid zip code using a regular expression in JavaScript

Thank you for the suggestions, everyone. I have made some modifications to the script based on your advice and it appears to be functioning correctly now. <script src="jquery-1.4.2.min.js" type="text/javascript"></script> <script> $ ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

All you need to know about the jQuery .css method

I've been struggling to get this script to function properly. Despite searching online, I haven't been able to find a satisfactory solution. $( document ).ready(function() { $("#container").click(function(){ var color = $(this).css("backgro ...

Creating layered images with CSS Grid

Visit this link for more details I've been attempting to create an overlap effect with 3 photos using CSS Grid. My desired outcome looks like this: Click here to see the desired result I followed tutorials that demonstrate the same method, but unfo ...