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

Are there alternative approaches to launching processes aside from the functions found in child_process?

Having trouble with NodeJS child_process in my specific use case. Are there other methods available to start processes from a node.js application? So far, Google has only been pointing me towards child_process for all of my inquiries. Edit I am looking to ...

Utilizing Angular 5 routerLink for linking to absolute paths with hash symbols

I am facing an issue with a URL that needs to be opened in a new tab. Unfortunately, Angular generates this URL without the # symbol. Currently, we have implemented the following: <!-- HTML --> <a title="Edit" [routerLink] = "['/object/objec ...

Troubleshooting Images in a React Application Integrated with WordPress API

I am struggling to understand why this GET request is consistently returning a 404 error. I have thoroughly tested the URL using Postman and everything seems to be in working order for the title and excerpt, but the images are causing some issues. Does a ...

Error encountered when attempting to initiate a second screenshare on Chrome due to an invalid state

I am interested in utilizing Screensharing in Chrome. After following a guide and creating an extension to access the deviceId for getUserMedia, I was able to successfully start streaming my screen. However, when I attempted to stop the stream using the pr ...

Error: The function "navigate" has not been declared or defined

Just starting out in reactjs and embarking on a new project. I've successfully implemented a register and login function using firebase, but hit a snag when trying to navigate to a new page like the dashboard upon user login, I encountered this error: ...

Master the art of returning two functions within a single function in Javascript with NodeJS and ExpressJS

Currently, I am facing an issue where I need to combine two objects and return them in one function. The challenge lies in the fact that both objects have almost identical properties, but different values. To tackle this problem, I created two separate fu ...

When utilizing jQuery.Mockjax to simulate the JSON data, the Backbone.Collection.fetch() function consistently results in a 404 error

My setup is pretty straightforward: Main.js: (function($) { "use strict"; var Company = Backbone.Model.extend({ defaults: { title: "", description: "" }, initialize: function() { ...

Tips for improving modularity in my frontend JavaScript code?

I'm currently developing a unique Node.js / Express application that visually represents text notes as a network to offer users a clear summary of the connections between different notes. The project heavily relies on frontend functionalities, requir ...

Is there a way to use the property of an object to perform a merge sort, rather than relying on an Array?

Query About Sorting JSON Object in JavaScript In search of the most efficient method to sort a large JSON object based on a specific property, I turned to JavaScript. My initial thought was to utilize a merge sort algorithm for this task due to its speed. ...

JavaScript function unable to execute form action properly

I have a link RESET YEAR which triggers a servlet to check if the current year is equal to the present year. If they are not equal, then the function resetyear() is supposed to be called. The issue I am facing is that the function is not working as expecte ...

"Adjusting Material UI Select Size - A Guide to Resizing Your

Struggling with getting Material UI selects to work properly with height and width using 'vh' and 'vw', as well as adjusting text size with 'vh'. The boxes have the correct size, but the label text is no longer centered due t ...

In PATCH requests, JSON data is not transmitted through Ajax

I'm attempting to send JSON data from the client to my server with the following code: $.ajax({ url : 'http://127.0.0.1:8001/api/v1/pulse/7/', data : data, type : 'PATCH', contentType : 'application/json' ...

Utilizing AngularJS to iterate over a single extensive unordered list

In my current Angular app, the JSON structure is as follows: 0: Object $$hashKey: "004" Date: "2014-04-17" Items: Array[3] 1: Object $$hashKey: "005" Date: "2014-04-18" Items: Array[3] 2: Object $$hashKey: "006" ...

Struggling to handle JSON response in JavaScript

Upon receiving a JSON response from the Amazon API, here is how it appears: { "Result": { "Data": { "Title": "HALO 3 (XBOX 360 - REGION FREE)", "FormattedPrice": "$19.95", "Source": "Product Description", "Content": "The epi ...

Develop a CakePHP CRUD view using a JavaScript framework

Creating a CRUD view in Cake PHP is simple with the following command: bin/cake bake all users This command builds the users table for CRUD operations. Is there a JavaScript framework that offers similar simplicity? ...

Newbie Inquiry Renewed: What is the best way to convert this into a functional hyperlink that maintains the data received from the ID tag?

I have no prior training etc. If you are not willing to help, please refrain from responding as I am simply trying to learn here. <a id="player-web-Link">View in Depth Stats</a> This code snippet loads the following image: https://i.stack.i ...

What is the best way to incorporate a for loop in order to create animations with anime.js?

I am currently working on implementing a for loop to create a page loader using JQuery along with the animation framework anime.js var testimonialElements = $(".loader-animation"); for(var i=0; i < Elements.length; i++){ var element = ...

What can you tell me about Page Event functionality in Datatables?

Curious question -- I'm currently seeking a practical example of how to implement a 'page' event in a project utilizing DataTables. The provided documentation can be found here -- http://datatables.net/docs/DataTables/1.9.4/#page. Despite t ...

The URL overwrites the Ajax transfer type

When making an ajax call using a generated URL from a paginator script, I encountered an issue. The URL was dynamically created as shown below: "http://192.168.1.23:8000/pricing/0/999/null/?page=9" A similar link is generated on the server: "https://xxx ...

Discovering all jQuery functions employed in a JavaScript file can be accomplished through the utilization of regular expressions

I have a somewhat unconventional idea that I want to share. The project I'm currently working on has an old front-end codebase that is causing the website to run slowly, with jQuery being a major factor. My plan is to develop a tool that can analyze a ...