Do not return true from a nested function in JavaScript for form validation

After successfully creating a function to validate a form, I realized that breaking it down into three separate functions would be more beneficial.

The challenge arose when attempting to return the 'false' message back to the form after splitting the functions. Initially, all errors were caught by various if statements in one big function, but now with functions within a function, getting that 'false' message back became confusing.

Below is the function called by the form submit button and the main function it invokes. Despite trying to use an empty variable as a placeholder for false, assigning it the value false within the validateSignup function did not yield the desired outcome.

function validateSignup()
{
 // Declaring Arrays (deleted array contents)
 var errorSpansArray=[whatever];   
 var regexErrorArray=[whatever];
 var regexArray=[whatever];

validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
passMatch();
genderCountryCheck()  
}

function validateText(formNumber, numberElements, errorSpansArrayName, regexErrorArrayName, regexArrayName)
 {              
     for (x = 0; x<numberElements; x++)
     {
         var spanName = errorSpansArrayName[x];
         var textError = document.getElementById(spanName);
         var y=document.forms[formNumber].elements[x];
         if (!y.value)
        {           
            errorMessage(0,spanName,x);
             return false;
        }
        if(!regexArrayName[x].test(y.value)){  
            textError.innerHTML = regexErrorArrayName[x];
            return false;

        }
    }

UPDATE: Appreciate the suggestions provided. I have managed to come up with a solution that seems effective for me.

 function validateSignup()
 {
 // Declaring Arrays (deleted array contents)
 var errorSpansArray=[whatever];   
 var regexErrorArray=[whatever];
 var regexArray=[whatever];

var returnValidateText=validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
var returnPassMatch = passMatch();
var returnGenderCountry = genderCountryCheck();

if (returnValidateText || returnPassMatch || returnGenderCountry === false)
    {
    return false;            
    }
    else{
    return true;    
    }

}

Answer №1

When the function is called, it will provide a value

   let checkForm = function verifyInput(....)

is what you need.

function confirmDetails()
{
     // Setting up Arrays (contents omitted)
     let errorMessages=[whatever];   
     let patternErrors=[whatever];
     let patterns=[whatever];

     let formValid = false;

    formValid = verifyInput(0,6,errorMessages, patternErrors, patterns);
    formValid = comparePasswords();
    formValid = validateLocation()  
}

Answer №2

To ensure the function returns are successful, one approach is to directly check each individual function and return based on the result of that check.

if (!validateText(0,6,errorSpansArray, regexErrorArray, regexArray)) {
  return false;
}
if (!passMatch()) {
  return false;
}    
if (!genderCountryCheck()) { 
  return false;
}

Alternatively, a more concise method involves using a single conditional statement like this:

return
  validateText(0,6,errorSpansArray, regexErrorArray, regexArray) &&
  passMatch() &&
  genderCountryCheck();

Answer №3

When using JavaScript, the "return false" statement indicates that the value returned at the method's location will be false. To achieve this functionality, you may need to implement code similar to:

If(validateText()){
    return true;
}

This pattern should be followed for the rest of the code as well.

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

The autocomplete feature in Codemirror seems to be failing specifically when writing JavaScript code

I am having trouble implementing the autocomplete feature in my JavaScript code editor using Codemirror. Can someone please help me figure out what I'm doing wrong? Here is the snippet of code : var editor = CodeMirror.fromTextArea(myTextarea, { ...

Ways to incorporate React.js into HTML for showcasing a portfolio

Having difficulties rendering my code using React.js for my portfolio. I am attempting to showcase my projects with images and p tags containing project titles and my role. Additionally, I would like the React elements to be clickable, directing users to t ...

The textbox is only enabled when a specific selection is made in the dropdown menu

My JavaScript code seems to be malfunctioning: <script language="javascript" type="text/javascript"> function ShowExpenseReport(Expense_Report_ID) { var width = screen.width; var leftpad = (width - 740) / 2; var jsopti ...

Determining the successful completion of an ajax request using jQuery editable plugin

I recently started using Jeditable to enable inline editing on my website. $(".video_content_right .project_description").editable(BASE_URL+"/update/description", { indicator: "<img src='" + BASE_URL + "/resources/assets/front/images/indicator ...

The eslint script encountered errors when running with meteor npm eslint command

After setting up Eslint, I encountered some errors that I couldn't quite figure out. When running meteor npm run lint, an error was thrown after completing the linting process. To fix this issue, I added the exit 0 attribute to gracefully exit the ...

What is the best way to extract data from two dropdown menus and send it to separate URLs?

I need assistance with extracting the selected year value from the first dropdown. I would like to append this value to the URL of the header page and also to the options in the second dropdown. This way, when I select a PHP page from the second dropdown ...

Preventing Parent CSS from Affecting Child Component CSS

I designed a React app that serves as a widget for easy inclusion on any HTML page. Unfortunately, I noticed that the CSS of this React app is being influenced by the CSS of the parent page it's placed in. I have a well-defined index.scss file where I ...

What could be causing the CastError: Cast to ObjectId failed in my code?

Whenever I try to access a specific route in my project, the following error is returned: Server running on PORT: 7000 /user/new CastError: Cast to ObjectId failed for value "favicon.ico" (type string) at path "_id" for model "User" at model.Query.exe ...

Utilizing AngularJS to Retrieve URL Parameters Within a Controller

I am attempting to retrieve URL parameters in my controller: Although I came across this example, I encountered an error that appears to be connected to the loading of necessary modules. app.controller('WidgetCtrl', ['$scope', '$ ...

Tips for making an input form that triggers an alert popup

After creating an HTML form with text input, utilizing Javascript for validation as shown below: I am trying to trigger an alert box thanking the user for entering data when the submit button is clicked. I have faced challenges in implementing this witho ...

Implementing JavaScript to override inline CSS styles

Is it possible to override inline CSS using JavaScript with compatibility for IE6? I came across a pure CSS solution, but unfortunately it doesn't work in IE. http://www.sitepoint.com/blogs/2009/05/27/override-inline-css/ <div class="block"> ...

Utilize the client's IP address as a cookie in order to recognize return visits and showcase a special message following the initial visit

First of all, a big thank you to anyone who can help resolve this issue. I apologize if this has been asked before (I couldn't find it anywhere, so I decided to post a new question). The main problem I am facing is getting my webpage to show an alert ...

Avoid triggering a keydown event if certain div elements have been clicked

When the user presses the space bar, my script is set up to perform certain actions, such as stopping an audio player: $('html').keydown(function(e){ if(e.keyCode == 32){ // Stop the audio player } } However, an issue arises when a ...

Geolocation ranking in Elasticsearch

I am experiencing constant errors with sorting in my elasticsearch query. The query is shown below: query { "query": { "bool": { "filter": { "geo_distance": { ...

Using next.js to fetch data can result in an endless loop of API

This specific code snippet is taken from the Next.js documentation and can also be accessed through the following link: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating. However, when attempting to fetc ...

Ways to activate ajax calls using a JavaScript chart

Newbie in the world of Javascript. I have a forced directed graph from spring.js and I am trying to trigger ajax from it when a user selects a node. However, I keep encountering an error: Uncaught SyntaxError: Unexpected token . The issue seems to be cente ...

Exciting animation in sidebar links text during toggle transition animation running

As the sidebar collapses, the text adjusts to its width in a choppy transition I'm seeking a way to display the text only when it fits perfectly within the sidebar without breaking into two lines I want the text to appear only after the collapse tra ...

What steps should I take to implement the features I want using Node.js?

My request is as follows: I need to pass an array of IDs to a function that will perform the following tasks: Check if a document exists in MongoDB. If it does, move on to the next ID. If not, create a document with the specified ID. If all the IDs ...

Error: Webpack encountering reference errors when handling multiple entry points

Here is my setup in webpack.config.js: entry: { a:'./src/a.js', b:'./src/b.js' }, output: { path: path.join(__dirname, 'dist'), filename: '[name].bundle.js' } The content of a.js includes: const ...

The React setState function isn't updating the state as expected when used within the useEffect hook

I'm new to using hooks and I'm facing an issue with setState when trying to update data received from an API. Despite logging the response data successfully, it seems that the state does not update as expected. My useEffect function is set to run ...