JavaScript form validation involves using client-side scripting to ensure that

I'm currently working on form validation, but I'm unsure if I'm overcomplicating things. I have a variable that compares elements and replaces an image with a checkmark for success or an X for failure upon successful validation. The function validateData is supposed to run when the field loses focus. However, the image source doesn't change when testing the first field with numbers to trigger the red X image source change.

function validateData() {
  var letters = /^[A-Za-z]+$/;
  var image1=document.getElementById("image1");

  if (document.forms["quiz_form"]["last_name"].value.match(letters) && document.forms["quiz_form"]["last_name"].value!="") {
    image1.src="check.png";
  } else {
    image1.src="redx.png";
  }
}
<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <meta name="author" content="Kenneth Dunn" />
    <meta name="description" content="" />
    <script src="quiz.js"></script>
    <link rel="stylesheet" href="quiz.css" type="text/css" />
  </head>
  <body>
    <div id="page">
      <div id="logo">
        <h1><a href="https://playoverwatch.com">Overwatch</a></h1>
      </div>
      <div id="content">
        <h2>Overwatch Quiz</h2>
        <p>
          Hi there!
          This quiz is dedicated to one of my favorite games, Overwatch! 
        </p>
        <form action="quiz.js" method="post" name="quiz_form">
          <p><br>
            <input name "first_name" type="text" placeholder="First Name"   onblur="this.placeholder='First Name'" onfocus="this.placeholder='Use only letters'" onblur="validateData()"/>
            <img src='http://www.q-park.ie/Portals/8/images/search-icon.png' id="image1" class="image1"/>
          </p>

          <p><br>
            <input name="last_name" type="text" placeholder="Last Name"  onblur="this.placeholder='Last Name'" onfocus="this.placeholder='Use only Letters'" onblur="validateData()" />
            <img src='http://www.q-park.ie/Portals/8/images/search-icon.png' id="image2" class="image2"/>
          </p>

          <p><br>
            <input name="email" type="text" placeholder="Email"  onblur="this.placeholder='Email'" onfocus="this.placeholder='Must contain @ '" onblur="validateData()"/>
            <img src='http://www.q-park.ie/Portals/8/images/search-icon.png' id="image3" class="image3"/>
          </p>

          <p><br>
            <input name="number" type="text" placeholder="Phone Number" onblur="this.placeholder='Phone Number'" onfocus="this.placeholder='Must follow xxx-xxx-xxx '" onblur="validateData()" />
            <img src='http://www.q-park.ie/Portals/8/images/search-icon.png' id="image4" class="image4"/>
          </p>

          <p><br>
            <input name="sulley" type="text" placeholder="Sulley Email" onblur="this.placeholder='Sulley Email Address'" onfocus="this.placeholder='Must contain ~ and https:// '" onblur="validateData()" />
            <img src='http://www.q-park.ie/Portals/8/images/search-icon.png' id="image5" class="image5"/>
          </p>
          <br>
          <br>
          <p>

          <h2>Find out which Overwatch character you are most like!</h2>

          <p>If you could pick what form to take in a fictional universe with magic and cool science what would you want to be?</p>

          <input type="radio" name="exist" value="1">Male(Human).<br>
          <input type="radio" name="exist" value="2">Female(Human).<br>
          <input type="radio" name="exist" value="3">An Animal or something crazy.

          <p>What is your preferred weapon to take on bad guys and defend yourself?</p>

          <input type="radio" name="weapon" value="1">Twin Shotguns for close range.<br>
          <input type="radio" name="weapon" value="2">Twin pistols medium range.<br>
          <input type="radio" name="weapon" value="3">An electro gun that shocks enemies into submission.

          <p>Which motivations most align with your own?<p>

          <input type="radio" name="idea" value="1">To become more powerful and to defeat those who would oppose me.<br>
          <input type="radio" name="idea" value="2">To explore the world and discover the unknown.<br>
          <input type="radio" name="idea" value="3">To protect my friends and those I care about.

          <p>What do you look like?</p>

          <input type="radio" name="look" value="1">Dark and mysterious black-hooded figure, very edgy, like people in the Matrix.<br>
          <input type="radio" name="look" value="2">Short and spunky British airforce pilot who can travel back in time.<br>
          <input type="radio" name="look" value="3">I'm a large gorilla who likes to eat bananas and peanut butter and can shield my friends from harm. 

          <br>
          <br>
          <input type="submit" name="submit" id="submit" value="submit" />
          <input type="reset" name="reset" id="reset" value="Reset" />
          </p>
        </form>
      <br>
      <br>
      <br>
      <br>

      <div id="footer">
        <h2 align="center" >Created by </h2>
        </p>
    </div>
    </div>
  </div>
</body>
</html>

Answer №1

To incorporate your JS script into the form, you cannot simply assign the action attribute. Instead, utilize the onsubmit event handler.

<form onsubmit="checkFormValidity">

By doing this, the checkFormValidity function will be called upon form submission. To prevent the form from submitting normally, you need to include a line in your function like this:

function checkFormValidity (event) {
  // stop the form from being submitted
  event.preventDefault();
}

Answer №2

There are numerous issues to address here, as pointed out by others. One major problem is the use of getElementsById instead of getElementById. If you're unsure how to access the developer console to identify errors, now is a good time to learn.

Implementing form validation can be quite complex, which is why I typically rely on a library to handle the heavy lifting. It may be worth considering incorporating one into your project.

Below is a functional version of what I believe you are attempting to achieve. While it may not be perfect, it's a solution I was able to quickly put together.

https://jsfiddle.net/ec2L08vf/1/

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

Simple CSS for creating a "red alert badge" with a number count

Looking for the best way to display the popular red notification indicator with count in a consistent manner across various browsers. It seems tricky to achieve a design that looks seamless on all platforms, as different browsers interpret paddings differe ...

Troubleshooting a jQuery issue involving socket.io

I recently created a chat room using socket.io and jQuery. Inexperienced with node.js, I uploaded the files to an old FTP to get it online. Upon loading the website, I encountered an error in the console: Uncaught ReferenceError: io is not defined at ...

Modify the appearance of a nested div using CSS hover on the main JSX container

Within the material-ui table component, I am dynamically mapping rows and columns. The className is set to clickableRow. The TableRow also includes a hover options div on the right side: const generateTableHoverOptions = () => { if (selected) { ...

POST request body is not defined

Client Interface: procedure OnButtonClick(Sender: TObject); begin gcm := GetGCMInstance; p := TJavaObjectArray<JString>.Create(1); p.Items[0] := StringToJString('460004329921'); FRegistrationID := JStringToString(gcm.register(p)); ...

Explore the functionality of the Enter key and search button with JavaScript

I have the following code that works perfectly when I click on the search button. However, I would like to know how I can also initiate a search using the enter key. Here is the code snippet: <script> function mySearch() { var text = document.g ...

ReactJS requires HTTP server to transpile babel code before running

I am a beginner when it comes to working with reactjs and I am currently in the process of setting up babel to execute babel code without having to serve HTTP files. Following the instructions on the Package Manager, I have successfully installed it along ...

``There seems to be an issue with JQuery.Ajax not properly displaying on Samsung Smart

I attempted to use JQuery.Ajax to interact with my webservice Below is the code snippet: Main.onLoad = function() { // Enable key event processing this.enableKeys(); widgetAPI.sendReadyEvent(); //$("#h2Test").html("Change On Text"); ...

What is the reason javascript struggles to locate and replace strings with spaces in a URL?

Let me begin by sharing the code I'm currently working on so that you can easily follow my explanations. Apologies for the French language used, as this website is being developed for a French-speaking school. I have eliminated irrelevant sections fro ...

The Strapi plugin seems to be encountering an issue as the API is not reachable, leading to a

In an attempt to create a custom API in Strapi backend, I developed a plugin called "test" for testing purposes. However, when trying to access the test response in Postman, it displays a 404 error stating that it is not accessible. Let me provide you wit ...

JavaScript: Creating a Function that Returns an Object with an Undefined `this.variable`

While using javascript, I encountered an issue with instance variables. Declaring a variable as "this.variable" works fine until my function returns an object. However, if the function returns a String or Number, there are no issues. But when it returns ...

Is it possible to close the navigation menu by clicking on a link or outside of the navigation area?

Hey everyone, I've recently dived into the world of web design and encountered my first hurdle. I need your expertise to help me solve this problem. How can I modify my JavaScript to close the NAV element by clicking on one of the links or outside t ...

Issue with updating Angular list reference when deleting an item

My current task involves implementing a feature that displays selected items from a hierarchical structure on the right side. slice.component.ts : import { Component, Input, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core&a ...

Retrieving the text content from a JSON key

I have the following JSON data saved in a jQuery variable called "jsondata": var jsondata = { "Name": { "Jaken": {}, "Test": {}, "Hello": {} }, "Date": { "Today": {}, "Tomorrow": {}, "Wednesday": {} }, "Description": { ...

What are some techniques for ensuring a CSS div remains stable and intact when adjusting the browser size?

Is there a way to prevent the entire website from resizing when you minimize or maximize your browser? I want the website size to adjust in proportion to your resize without reorganizing everything. How can this be achieved while maintaining the site lengt ...

Angular // binding innerHTML data

I'm having trouble setting up a dynamic table where one of the cells needs to contain a progress bar. I attempted using innerHTML for this, but it's not working as expected. Any suggestions on how to approach this? Here is a snippet from my dash ...

Why does jQuery's each function struggle to retrieve the width of hidden elements?

Why is it difficult to obtain the width of hidden elements? Here is my code: .hidden { display: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <ul class="navbar-items"> <li> ...

Leverage Firebase cloud functions to transmit a POST request to a server that is not affiliated with

Is it feasible to utilize a firebase cloud function for sending a post request to a non-Google server? It appears that being on the blaze plan is necessary in order to communicate with non-google servers. Essentially, I aim to perform a POST action to an ...

Adding elements to a multi-dimensional array that match elements from another array

I am working with two arrays: a = [ [a, b], [c, d], [e, f], [g, h] ] b = [ [a, 4], [1, 2], [e, 3] ] My challenge lies in updating the elements of array a when they match corresponding elements in array b. Specifically, I need to add a new ...

View the selected radio buttons and checkboxes next to each other in real-time before finalizing and submitting

Within my form, individuals have the option to select from radio buttons and checkboxes. The challenge is that I need to display the chosen data on the page before they enter their email and submit! Since I cannot refresh the page, PHP won't work for ...

What is the best way to reset the scroll position of a div when you stop hovering over a link?

Can anyone help me figure out how to reset the scroll wheel when hovering over dropdown menu items? I've tried multiple solutions found online, but none seem to be working for me. If you have any ideas on how to accomplish this, please let me know! f ...