What is the proper way to connect my JavaScript code to my HTML form?

My JavaScript function is not working properly when I try to submit a form on my website.

<form onsubmit="validateRegistration()">

    <p>
     // Email registration
    <input type="text" id="e-mail" placeholder="Email" />
  </p><p>
    // Password registration
    <input type="text" id="pswd" placeholder="Password" />
  </p>
    <br>
    <input type="submit" class="submit">
  </form>

I have made multiple attempts to link the JavaScript code with the HTML form, but whenever I click the submit button, none of the error alerts are displayed as expected.

// HTML
<form onsubmit="validateRegistration()">

    <p>
    <input type="text" id="e-mail" placeholder="Email" />
  </p><p>
    <input type="text" id="pswd" placeholder="Password" />
  </p>
    <br>
    <input type="submit" class="submit">
  </form>

// JavaScript 
// Main Function
function validateRegistration(){
  var email = document.getElementById('e-mail').value;
  var password = document.getElementById('pswd').value;

  var emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

  var emailResult = emailRegex.test(email);

  if(emailResult == false){
    alert("Please enter a valid email address");
    return false;
  }

  var lowerCaseLetters = /[a-z]/g;
  if(!password.match(lowerCaseLetters)) {
    alert("Password must contain at least one lowercase letter!");
    return false;
  }

  var upperCaseLetters = /[A-Z]/g;
  if(!password.match(upperCaseLetters)){
    alert("Password must contain at least one uppercase letter!");
    return false;
  }

  
  var numbers = /[0-9]/g;
  if(!password.match(numbers)){
    alert("Password must contain at least one number!");
    return false;
  }

  var specialCharacters = /[!@#$%^&*(),.?":{}|<>]/g;
  if(!password.match(specialCharacters)){
    alert("Password must contain at least one special character!");
    return false;
  }

  if(password.length < 8){
    alert("Password must be at least 8 characters long");
    return false;
  }
}

I am expecting the JavaScript code to display error messages when an invalid password is submitted and to show a "Thank you" message when both a valid email and password are submitted correctly.

Answer №1

Oluwafemi suggested putting an event listener on the 'submit' event instead, which could be more efficient. Placing the event on the submit button allows you to halt it during the click event without triggering the form submission. By updating your code in this way, troubleshooting may be easier in the future.

Adjusting your code is a simple task. First, update your form structure as shown below:

<form id="form">
    <p>
    <input type="text" id="e-mail" placeholder="Email" />
  </p>
  <p>
    <input type="text" id="pswd" placeholder="Password" />
  </p>
  <br />
    <input id="submitButton" type="submit" class="submit">
  </form>

Add the following code after your javascript function:

document.querySelector("#submitButton").addEventListener("click", function(event) {
         event.preventDefault;

         validateReg()
}, false);

This snippet prevents the form submission and performs the necessary validation checks. For further details, refer to the Mozilla developer site.

To handle successful validations, include

document.getElementById('form').submit();
in any return statement set to true.

The updated code sets the submit button as default functionality, with failing checks returning false:

//Javascript 
//Main Function
function validateReg() {

  var email = document.getElementById('e-mail').value;
  var password = document.getElementById('pswd').value;

  var emailRGEX = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

  var emailResult = emailRGEX.test(email);

  //validate Email
  if(emailResult == false){
    alert("Please enter a valid email address");
    return false;
  }

  //validate lower case
  var lowerCaseLetters = /[a-z]/g;
  if(password.match(lowerCaseLetters) == null) {
    alert("Password needs a lower case!");
    return false;
  }

  //validate upper case
  var upperCaseLetters = /[A-Z]/g;
  if(password.match(upperCaseLetters) == null){
    alert("Password needs an upper case!");
    return false;
  }

  //validate numbers
  var numbers = /[0-9]/g;
  if(password.match(numbers) == null){
    alert("Password needs a number!");
    return false;
  }

  //validate special characters
  var special = /[!@#$%^&*(),.?":{}|<>]/g;
  if(password.match(special) == null){
    alert("Password needs a special character!");
    return false;
  }

  if(password.length < 8){
    return false;
  }

  document.getElementById('form').submit();
}

Answer №2

An effective approach is to include an event listener in your JavaScript file that listens for the 'submit' event before executing your function.

Additionally, make sure to link your JavaScript file within a script tag in your HTML document. This should be successful provided your logic is accurate.

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

Sending data from a Node.js backend to a React.js frontend using res.send

How can I pass a string from my nodejs backend using res.send? app.post("/user", (req,res) => { console.log(req.body.email); res.send('haha'); }); I need to perform certain operations on the front end based on the value of the string retriev ...

Steps for performing position by position sorting within an array of arrays of numbers using the Lodash library

My task involves sorting an array of strings: ['1.2.3', '1.5.2', '1.23', '1.20.31'] I am looking for a way to sort the array by splitting each string separated by dots, such as 1.2.3 into ['1','2&apo ...

Error: Property 'barcodeScanner' is not readable

Currently, I am utilizing barcodescanner.js for scanning QR codes. I have successfully downloaded and linked the CaptureActivity android library to my project. However, when attempting to execute the following code: window.plugins.barcodeScanner.scan(sca ...

Vue js parent-child communication using event bus fails to function

Is there any way to successfully communicate between non parent child components in vue js document? I followed the instructions in the vue document, but unfortunately, my code did not work as expected. Below is a snippet of my code: The structure of the ...

The function 'create' is not a recognized property within the 'Completions' type

Recently, I've been experimenting with ChatGPT and have just installed the latest version 4.8.0. My current project is built on NextJS. Prior to this, I successfully completed a project using v3.something last month, but I'm encountering diffic ...

After my jQuery functions are executed, my CSS rules are loaded

Struggling with the communication between CSS and jQuery, I find myself torn. In CSS, my rules are often very specific, like this: div#container > div#contentLeft { //Code here } However, when I add jQuery to spice up my site, the CSS rules seem to ...

Updating Cart Array in Angular 4 when Adding a New Item

I'm currently using angular 4 and I have encountered an issue in the code where adding a new product to the cart overwrites the existing item instead of appending it to the array. Here is a screenshot illustrating the problem cart.service.ts export ...

The index.html file is failing to load/render when using app.js

I am currently in the process of creating a to-do list using an older tutorial. The app.js file seems to be functioning properly, however, when I try to run it locally, all I see is a blank page instead of my HTML content. Here is the code found in the ap ...

When utilizing the built-in filter in Angular 2 ag-grid, the Clear Filter button efficiently removes any text from the filter box without needing to refresh the

When using ag-Grid's default filter feature, I noticed that the clear filter button only clears the text box and does not automatically refresh the column, even when the 'clearButton' and 'applyButton' parameters are set to true. T ...

JSON failing to show all values sent as a string

In a div element there is a table with 3 rows, a textarea, and a button. The JSON data populates the first 3 rows correctly but the textarea remains blank. My goal is to display the previous record from the database in the textarea. function ChangeLoadin ...

Alternate routing based on conditions in Angular

I've used the "$urlRouterProvider.otherwise('{route here}')" syntax in angular to create a catch-all route in Angular UI-Router. One thing I'm curious about is whether it's possible to have conditional "otherwise" routing based o ...

Dealing with multi-line strings in Javascript

I am having an issue with my code: let testStr = "Asdfads"; let htmlStr = `<script>${ testStr }</script>`; // but it works with: <div>${ testStr }</div> console.log(htmlStr); When I run this code, I receive the following error: ...

What is the best way to trigger a refresh callback on Angular datatable pagination after updating the data

I've successfully set up my angular datatable configuration. Here's what it looks like: vm.dtOptions = DTOptionsBuilder.newOptions(). withPaginationType('full_numbers'). //withOption('ajax', { ...

The output of PHP is not being captured by Ajax

I have a JavaScript code that calls a PHP script to retrieve a value, but it's not working as expected. Here is my JavaScript code: $.ajax({ type: 'GET', url: '/home/example.com/ftp/www/typo3conf/ext/quiz_rs/pi1', data ...

"Deploying code to Heroku using Node.js: A guide to adding git commits directly on

Currently, as I delve into learning Node and Git, I'm faced with a dilemma involving my Heroku app. The app is designed to interact with a local file on the server that serves as a basic JSON database. The issue arises when I attempt to manage this f ...

Updating and Preserving Content in Angular

I've encountered an issue while working on a code that allows users to edit and save a paragraph on the screen. Currently, the editing functionality is working fine and the save() operation is successful. However, after saving, the edited paragraph do ...

A guide on invoking a function within a nested or local function

When the code below is executed in a local function, such as the one inside s3.getObject, it throws an error stating that setState is not a function. s3.getObject({ Bucket: bucket, Key: key }, function (error, data) { if (error != ...

Create dynamic connections between animated sprites using Three.js

I am attempting to insert lines between animated sprites, similar to the example provided. Despite trying various solutions, I have been unsuccessful in creating either a dynamic or static line between these animated sprites. Is it feasible to generate a d ...

"Activate the parent window by navigating using the accesskey assigned to the href

I have integrated a bank calculator tool into a website. The calculator opens in a new window, but I am encountering an issue. Users need a shortcut to open the calculator multiple times. I have discovered the accesskey feature, which works the first tim ...

Sequelize encountered an error: getaddrinfo ENOTFOUND (even though the address is correct)

I've encountered some Sequelize errors while attempting to deploy a site I developed using Angular and Express/Sequelize. Here's the issue: Everything works perfectly on my local WAMP server, connecting to the local database without any problems ...