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

Incorporate concealed image into HTML

When I perform actions with a couple of images, I encounter delays because the browser needs to load the images. For example, if I use $('body').append(''); everything works smoothly without any delays. However, when I try using style= ...

Moving an array in AngularJS from one file to another

As someone new to AngularJS, I am facing an issue with integrating two separate files that contain modules. Each file works fine individually - allowing me to perform operations on arrays of names. However, when switching views, the arrays remain stored un ...

Validating minimum and maximum values with Angular 2 FormBuilder

I am currently developing a form using Angular 2 Formbuilder and I want to ensure that users can only input positive values into the amount field (with a minValue of 0 and maxValue of 100). How can I go about implementing minimum and maximum value validati ...

To enhance user experience, it is recommended to reload the page once

Hello, I'm looking for a way to automatically refresh the page after submitting an AJAX form. Currently, I have an onClick function that seems to refresh the page, but I still need to press F5 to see the changes I've made. Here's the JavaSc ...

Utilizing ElementRef in Angular 4 to close dropdown when clicking outside of it

I recently came across this helpful tutorial, but I'm having trouble grasping how it actually functions. Here's the code snippet I've incorporated into my TypeScript file: @Component({ host: { '(document:click)': 'onOuts ...

Is it possible for JavaScript to only work within the <script> tags and not in a separate .js

I'm facing a puzzling issue with my JavaScript code. It runs fine when placed directly within <script>...code...</script> tags, but refuses to work when linked from an external file like this: <SCRIPT SRC="http://website.com/download/o ...

Designing an image transformation page by segmenting the image into fragments

Does anyone have insight into the creation process of websites like this one? Are there any plugins or tools that can assist in building something similar? ...

Learn the method to duplicate Outer HTML with the use of jQuery or Pure JavaScript

I have successfully copied the value of an input into the clipboard using the first part of the solution provided. However, I am now trying to figure out how to copy HTML content like an entire <p> tag. Currently, when attempting this, I am encounter ...

What could be causing my selenium tests to fail on travis-ci even though there have been no code changes, when they are passing successfully

I'm facing a tough challenge trying to troubleshoot a selenium test that passes when run locally but not on travis. Reviewing the travis build logs, I noticed that the test was passing in build #311 but started failing at build #312. It seems like th ...

Binding textarea data in Angular is a powerful feature that allows

I am looking to display the content from a textarea on the page in real time, but I am struggling to get the line breaks to show up. Here is my current code snippet: app.component.html <div class="ui center aligned grid">{{Form.value.address}}< ...

Enforce file selection using AngularJS based on certain conditions

When data is received from the backend in JSON format, it looks like this: { "data":{ "xyz":[ { "number":"1", "short_text":"Sign Contract", "long_text":"Enter names after contract signing", "is_photo":false ...

Managing numerous range sliders in a Django form

My Request: I am looking to have multiple Range sliders (the number will change based on user selections) on a single page. When the sliders are moved, I want the value to be updated and displayed in a span element, as well as updating the model. The Issu ...

Scroll to the end of the main div's horizontal position instead of using offset().left

I'm struggling with an issue in my code. <script type="text/javascript"> $(function() { $('ul.nav a').bind('click',function(event){ var $anchor = $(this); /* ...

What steps can I take to stop jQuery's $.getJSON function from converting my AJAX response keys into integers?

I am facing an issue where JQuery is changing the type of keys in a JSON response object from text to integer when populating a select box. This causes the response object to be reordered based on the numeric indexes, disrupting the order of the select box ...

Use jQuery to apply a class to some input elements when certain events like keyup or

If I type something in the input field, it should add a border to the li tag containing the text. The current script works fine, but is there a way to make this jQuery script shorter? Thank you for your help! .add_border{ border: 2px solid #000 !impor ...

What is the purpose of requiring the explicit invocation of app.listen(port) to enable express-ws to function properly?

I've recently started exploring NodeJS Express and came across the official tutorial from express-ws for setting up websockets in a simple project generated using npx express-generator. While following the tutorial, I noticed that in the app.js file, ...

Error: JavaScript object array failing to import properly

In my code, I have an array of objects named trace which is defined as follows: export const trace: IStackTrace[] = [ { ordered_globals: ["c"], stdout: "", func_name: "<module>", stack_to_render: [], globals: { c: ["REF" ...

Problem with Vue JS Hooper Image Slider (integrated into NuxtJS application)

Issue with Loading Images I encountered a problem while using the carousel feature in this GitHub project (). The images in the carousel do not display on the first load; instead, a loader animation image appears. However, upon refreshing the page, the ca ...

Master the Art of Animating Letters in the DOM by Navigating Through Any Array of Characters

I am attempting to implement a typewriter effect animation where a new message is displayed and animated as I type into an input box. Initially, I tried using a global char variable to iterate through each element of the array. However, whenever I passed ...

Utilizing vuetifyjs: Selectively incorporating necessary icons into the build

I am currently working on a vuetifyjs-app using the default "Material Design Icons". For the production build, I am only utilizing 2 icons from this font (which are being used by the vuetify-component chips). Following recommendations, I have included the ...