Implementing JavaScript if statements that evaluate to true without cycling through all my if statements

Hey everyone, I've encountered an issue with my code. When testing each part individually, everything works fine. However, when all parts are combined and the first IF statement is reached, the form gets submitted without validating the others. Can anyone help me restructure my code so that it runs all IF statements before returning true?

Below is the code snippet:

    if (this.element.find('#visitdate').length > 0) {
    var dateParts = $('#tvisitdate').val().split('/');
    var check = new Date(dateParts[2], dateParts[1]-1, dateParts[0], 0,0,0,0);
    var d = new Date();
    var today = new Date(d.getFullYear(), d.getMonth(), d.getDate());

    if (today.getTime() > check.getTime() ) {
        _errMsg = "Please enter a future visit date";
        return false;
    } else {
        return true;
    }
}

if (this.element.find('#birthdate').length > 0) {
    var dateParts1 = $('#birthdate').val().split('/');
    var check1 = new Date(dateParts1[2], dateParts1[1]-1, dateParts1[0], 0,0,0,0).getFullYear();
    var today1 = new Date();
    var year = today1.getFullYear();

    if (check1 >= year) {
        _errMsg = "Please enter a valid date of birthday";
        return false;
    } else {
        return true;
    }
}

Answer №1

To optimize the code and have only one return statement, a boolean (true/false) variable is used to track errors throughout the code:

var hasError = false;
if (this.element.find('#visitdate').length > 0) {
    var dateParts = $('#tvisitdate').val().split('/');
    var check = new Date(dateParts[2], dateParts[1]-1, dateParts[0], 0,0,0,0);
    var currentDate = new Date();
    var today = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());

    if (today.getTime() > check.getTime()) {
        errorMessage = "Please enter a future visit date";
        hasError = true;
    }
}

if (this.element.find('#birthdate').length > 0) {
    var dateParts1 = $('#birthdate').val().split('/');
    var check1 = new Date(dateParts1[2], dateParts1[1]-1, dateParts1[0], 0,0,0,0).getFullYear();
    var currentYear = new Date().getFullYear();

    if (check1 >= currentYear) {
        errorMessage = "Please enter a valid date of birth";
        hasError = true;
    }
}
return !hasError;

Answer №2

It is advisable to avoid using the return statement for every if condition. Instead, consider assigning a boolean value for the first if statement and then proceed to evaluate the second if condition based on this initial value. Update the boolean value as needed according to the condition and finally return this updated value at the end of the process.

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

Enhancing the Calculator Functionality in a React Program

I'm struggling to incorporate a reset button into the input field, similar to CE on a calculator. I'm facing challenges when it comes to integrating it within the existing code structure. import { useRef } from "react"; import './A ...

Encountering a CouchDB 401 Unauthorized Error

I have a couchDB database named "guestbook". Initially, I utilized the following code to add a user to the "_users" database: $scope.submit = function(){ var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name; console.log(url); $ht ...

Is there a C++ equivalent to the JS Array.prototype.map method?

When it comes to JavaScript, Array.prototype.map is a powerful tool for creating a new array by applying a function to each element. Consider the following example: const elements = [{ text: 'hi1' }, { text: 'hi2' }, { text: 'hihi ...

Unable to use the res.send() function

I've been working on a Node.js project. Within the validate.js file, I have defined a class Validate with a static method validateTicket and exported the class at the end. validate.js file const request = require("request"); const config = { urlBas ...

Is there a way to decrease the speed of a range slider?

Recently, I created a range slider using HTML, CSS, and JS to complement my Lua Nui. It's been working smoothly for the most part, but I've noticed an issue when sliding too quickly on the slider. As I slide it to the left, certain values fluctua ...

What is the best way to post an image using nodejs and express?

Recently, I've been working on a CMS for a food automation system and one feature I want to incorporate is the ability to upload pictures of different foods: <form method="post" enctype="multipart/form-data" action="/upload"> <td>< ...

Ionic, Angular - A component with two out of three inputs displaying undefined values

I am facing an issue with the @input() in my code. Two out of three inputs have undefined values when I try to use them, although they can be displayed using interpolation in the template file. .ts : export class NoteCanvasPageComponent { @Input() note ...

What is the process for running an HTML file on a server that utilizes Cordova plugins?

I'm a beginner in Cordova and recently I created an HTML file which I added to the xampp/htdocs directory and it worked fine. My goal is to create a generic app, but now I want to incorporate the Camera Plug-in into my app. Unfortunately, I am unable ...

Using discord.js does not allow line breaks in embed descriptions

const chatRoom = replyOptions.getRoom("room"); const header = replyOptions.getHeader("header"); const content = replyOptions.getContent("text"); const chatEmbed = new MessageEmbed() .setColor('DARK_VIVID_PURPLE') ...

Using JavaScript to Capture a Webpage Element as an Image

Although this question has been asked in the past, I am hoping for updated information since all the answers are from a few years ago. While searching, I came across https://github.com/apollolm/phantasm, which seems to be exactly what I need. However, it ...

Receiving an error when attempting to utilize a value from the .env file in createSecretKey function

Currently, my code looks like this: const secretKey = crypto.createSecretKey( Buffer.from(process.env.SECRET, "hex") ); However, I am encountering the following error message: "The value of 'key.byteLength' is out of range. It must be > ...

Stop displaying AJAX requests in the console tab of Firebug, similar to how Twitter does it

I'm looking for a way to prevent my AJAX calls from being logged in Firebug's Console tab, similar to how Twitter does it. When using Twitter search, you'll see a live update feed showing "5 tweets since you searched." Twitter sends periodic ...

Locate the initial ancestor element, excluding the parent element that comes before the root ancestor

My HTML structure is as follows: <div> <ul> <li> <div>Other elements</div> <div> <ul> <li class='base-parent parent'> <div>Base Parent ...

Clicking the button to send the form using JavaScript

Currently, I am dealing with a shopping cart plugin that relies on a basic form on the product page to send values such as price and product name. However, I am facing an issue where this plugin uses a standard submit button to transmit the values, and I w ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

Crafting an integrated REST API model with interconnected data

This question revolves around the implementation of a specific scenario rather than a problem I am facing. Let's say we have a User and a Resource, where a User can have multiple Resource but a Resource can have only 1 User. How should API endpoints b ...

How can I best access the object being exposed on the webpage using <script type="text/json" id="myJSON">?

In our current project, we are successfully using AMD modules to organize and structure our code. One idea I have is to create an AMD module that accesses a script tag using a jQuery ID selector and then parses the content into JSON format. Here's an ...

What is the best way to update React State after making an asynchronous call to MongoDB?

I have been facing a common issue, but couldn't find an up-to-date solution on Stack Overflow specifically for React/Meteor. My goal is to query a mongoDB to retrieve data and then pass it into the state of my React components. Currently, I am queryin ...

Verify the occurrence of an element within an array inside of another array

Here is the scenario: const arr1 = [{id: 1},{id: 2}] const arr2 = [{id: 1},{id: 4},{id: 3}] I need to determine if elements in arr2 are present in arr1 or vice versa. This comparison needs to be done for each element in the array. The expected output sho ...

Obtaining the node generated from a document fragment

Suppose I add a document fragment to the DOM in the following way: const ul = document.querySelector("ul"); const fruits = ["Apple", "Orange", "Banana", "Melon"]; const fragment = new DocumentFragment(); ...