Preventing form submission with JavaScript by implementing multiple validation checks

Preventing a form from submitting when validation returns false is possible.

Here's an example:

<form name="registration" action="registration.php" onsubmit="return validate()">
    <!-- some inputs like: -->
<input type="text" id="username" name="username">
<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">
    <!-- and some others... -->
</form>

The javascript function 'validate()' contains various checks as follows:

function validate() {
    checkUsername();
    checkPassword(); 
    checkFirstname(); 
    checkLastname();
    checkBirthdate();
    checkEmail();
    checkPhone();
}

If one of the validations fails, you want the form not to submit. One approach can be to modify the 'validate()' function:

function validate() {
    var truth1 = checkUsername();
    var truth2 = checkPassword(); 
    var truth3 = checkFirstname(); 
    var truth4 = checkLastname();
    var truth5 = checkBirthdate();
    var truth6 = checkEmail();
    var truth7 = checkPhone();
    return (truth1 && truth2 & truth3 & truth4 & truth5 & truth6 & truth7);
}

If your form still submits despite returning false, consider checking for any syntax errors in your code.

Another solution could involve changing how your checks are evaluated within the 'validate()' function.

Answer №1

Each of your

unique field validation functions
needs to output a boolean value.

Then, your

comprehensive form validation function
will look like this:

function validateForm() {
    var validations = [
        validateUsername,
        validatePassword,
        validateFirstName,
        validateLastName,
        validateBirthdate,
        validateEmail,
        validatePhone,
    ].map(function(validation) { return validation(); });

    return (validations.indexOf(false) === -1);
}

With this approach, the validateForm function will now return false if any field is considered invalid, and true if all fields meet the necessary criteria.

Answer №2

Utilize the Array.prototype.every() method to execute each function; if any function returns false, the .every() call will return false.

<form name="registration" action="registration.php">
    <!-- various input fields like: -->
<input type="text" id="username" name="username">
<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">
    <!-- and more... -->
</form>

function validate() {
    return [checkUsername, 
      checkPassword, 
      checkFirstname, 
      checkLastname, 
      checkBirthdate, 
      checkEmail,
      checkPhone].every(function(check) {return check()});
}

document.querySelector("[name=registration]")
.onsubmit = function(event) { 
  event.preventDefault();
  if (validate()) { this.submit() }
  else { // notify user which fields are invalid }
}

Answer №3

To ensure that the "validate" function only returns a "true" boolean result when every single check function returns true, we need to make modifications to the current code.

One approach is to update each line in the existing "validate" function with something similar to the example below.

bUsernameCheck = checkUsername();
if !bUsernameCheck { return false };
...
<perform other checks>
...
return true;

The new and improved "validate" function will only provide a positive outcome if all individual input validation checks pass successfully.

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 PHP Comet feature is causing the page to experience delays in reloading

Hello, I am working on implementing comet functionality using PHP and jQuery. The comet starts with every page load, but this seems to be causing a significant delay in loading any page on the website, taking about 10 seconds. It appears as though the page ...

Enhancing Bootstrap with VueJS for better component ordering

I've been struggling with Vue components in Bootstrap lately. I am attempting to create collapsible Bootstrap content in Vue, and here is the current code: HTML <div class="col-sm main-content" id="main-content"> <p&g ...

Problem with Angular 2 Typings Paths in Typescript

Currently, I am in the process of learning how to create a Gulp build process with Angular 2 and Typescript. Following the Quick Start guide has allowed me to get everything up and running smoothly. However, I have decided to experiment with different fold ...

Learn how to implement a conditional class binding in Vue 3, and discover how to apply additional classes when a specific condition is met

As a newcomer to Vue.js 3, I am wondering how to implement a conditional class binding in Vue 3. Specifically, I would like to achieve the following logic: if router.path != '/', then add the class 'nav-bar-two'; otherwise, do not apply ...

Employing an item as a function

My query pertains to utilizing an express application object (app object) as a callback function. The express application is known for its methods and properties that aid in handling HTTP requests. When integrating the app object with an HTTP server, it se ...

Encountering Error with Axios in Nuxt while Navigating Pages

Working on a nuxt application utilizing axios for API calls. In my index.vue file, I have the code snippet below. <template> <div> <Hero /> <Homebooks :details="details" /> </div> </template> <s ...

Prevent the need to go through the keycloak callback process each time the page is

I have integrated keycloak as an identity provider into my React application. I successfully added the keycloak react dependency via npm. Below are the versions of the keycloak react npm modules on which my application depends : "@react-keycloak/web ...

Tips for resolving the 'node is not defined' error in the case of passing a default value

Attempting to incorporate the Trie data structure into JavaScript has presented a challenge. Within the print function, which displays an array of all words in the Trie, there is a search function that looks for words within the Trie and adds them to the a ...

Detecting the Escape key when the browser's search bar is open - a step-by-step guide

One feature on my website is an editor window that can be closed using the Escape key. The functionality is implemented in JavaScript: $(document).keyup( function(e) { // Closing editor window with ESCAPE KEY if(e.which == 27) { // Clic ...

Preparing user context prior to executing controllers within AngularJS

I recently created an AngularJS application and integrated a REST API to fetch resources for the app. As part of the authentication process, I store the user's access token in a cookie. When the user reloads the page, I need to retrieve user informati ...

PHP Multiple Uploads is a feature that allows users to

I'm currently attempting to utilize the dropzone JS plugin in combination with PHP for the purpose of uploading multiple files and then displaying each file's URL. Here is my progress so far: $upload_dir = 'files'; for($i=0; $i&l ...

Launch the game within the gaming application

I am looking to incorporate a game within another game... Here's what I mean: Open the app: Pandachii Next, navigate to the 4th button (game pad). When we click on the game icon, I want to launch another game (located below the Pandachii window - c ...

Utilizing ES6 array methods to convert multidimensional arrays into chart-ready data

Seeking help with converting an array to a specific data format for chart display. The chrart.js library requires data in the following format: dataset = [ { label: 'one', data: []}, {label: 'two', data: []} ]; I ...

How to retrieve the outcome of a stored procedure using node.js

Is it possible to retrieve multiple select results from distinct tables (many rows) in just one stored procedure in mysql and then access those results in nodejs? In .NET with SQL Server, we can use "sqlnextresult" for this purpose. VIEW IMAGE FROM STORE ...

Adjust the size of a panel in Extjs when its parent div is resized

Within my div, I have included an Extjs panel using the renderTo configuration option. Can someone please advise on how to adjust the panel size dynamically when the div is resized? Appreciate any help! Thank you. ...

The overflow of Highcharts tooltips is set to be hidden

My issue arises when the chart drawing area is smaller than a highchart tooltip, causing part of the tooltip to be hidden as it overflows the chart. I would like the tooltip to remain visible at all times, regardless of the size of the chart area. I have ...

Printing reports in Angular 9

I have a requirement in my Angular 9 application to generate and print reports. 1. I am looking for suggestions on how to handle printing reports where a user triggers the action by clicking a button, and the report data needs to be fetched from the datab ...

Selecting items from a list at random using the power of math.random() and math.floor()

When attempting to randomize the popping of elements in a list stored in the baby variable, only baby[1] is being popped. How can I make it pop random elements? <body> <h1 id="1">bebe</h1> <h1 id="2">t ...

mapStateToProps was invoked, however componentDidUpdate did not trigger

Working on fetching data for GameChart from an API and updating the Redux state. In my GameChart.jsx file, I have a chart that gets rendered when componentDidUpdate is called. However, there are times when changing the Redux state does not trigger componen ...

Error in THREE.js: Unable to access property 'lib' from an undefined source (THREE.ShaderUtils.lib["normal"])

I have been working on the challenges provided in the WebGL introductory book by Oreilly. Encountered a runtime error with the following code snippet. After searching online, it seems like I am the only one facing this issue. Could you please assist me in ...