Prevent form submission when email is missing

function validateEmail(){

     var TCode = document.getElementById('email').value;


     if(TCode.length==0)
     {
         email_info.innerHTML="This field is required";
         return false;
     }
        email_info.innerHTML=" ";
        var atpos=TCode.indexOf("@");
        var dotpos=TCode.lastIndexOf(".");
        if (atpos<1 || dotpos<atpos+2 || dotpos+2>=TCode.length)
          {
             email_info.innerHTML="Not a valid e-mail address";
          return false;
          }
         email_info.innerHTML=" ";
            var xmlhttp;    

        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
             xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
                xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                 document.getElementById("email_info").innerHTML=xmlhttp.responseText;

            }
          }

        xmlhttp.open("GET","get_email.jsp?email="+TCode,true);
        xmlhttp.send();


        return true;  

}

On blur of an email input field, the function above is called to validate the email. However, the issue arises when attempting to restrict form submission if the email already exists in the database. While it's possible to display a message if the email exists, preventing the form from submitting is challenging. Any suggestions on how to solve this problem?

Answer №1

To begin, a variable is initialized as false.

window.canSubmitEmail = false;

If the email passes validation, the variable is set to true:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
  document.getElementById("email_info").innerHTML=xmlhttp.responseText;
  window.canSubmitEmail = true;
}

When the form is submitted:

<form onsubmit="return validateForm()" />

The value of the variable is returned:

function validateForm(){
  return window.canSubmitEmail;
}

Furthermore, if an incorrect email is provided and then corrected, the variable is reset to false:

if (atpos<1 || dotpos<atpos+2 || dotpos+2>=TCode.length)
{
  email_info.innerHTML="Not a valid e-mail address";
  window.canSubmitEmail = false;
  return false;
}

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 issue of drop shadows causing links to not work properly in Internet Explorer

I am currently working on a website design that features a fixed menu positioned behind the body. When the menu icon is clicked, some jQuery code shifts the body to the left. To create the effect of the fixed menu being positioned underneath, I have added ...

What are some ways to prevent "window.onbeforeunload" from appearing when a form is submitted?

Is there a way to prevent the alert box from appearing when submitting a form using the Submit button below? I want to avoid being prompted to "Leave this page" or "stay on this" after submitting the form. <script> window.onbeforeunload = ...

Updating Ruby on Rails variable using JQuery

I am managing a ruby on rails website where I have implemented a variable called @number. This variable retrieves a number using an API and then showcases it on the site. The issue I am facing is that the number only updates when the page is refreshed. I ...

reduce the size of the image as the browser width decreases

Struggling with a webpage layout that features an image on the left and content area on the right, both with fixed widths. When reducing browser width, the image should not shrink but be cropped from the left side instead. Any solutions for this issue? ...

What is the best way to display data retrieved through Ajax, jQuery, and JavaScript on an HTML page

I have successfully used the script below to fetch data from an api endpoint and populate my charts. Now, I want not only to display the data in my charts but also directly output it in my HTML code using something like the document.write() function. How ...

Troubles with AJAX and jQuery

<html> <head> <title>Ajax Example</title> <script type="text/JavaScript" src="jquery-1.5.1.min.js"></script> <script type="text/JavaScript"> function fetchData() { $.ajax({ type: "GET", url: "htt ...

What is the best way to send a POST parameter using JavaScript?

Attempting to submit a variable and its name through a form, I had to change the button type to "button" instead of "submit" for additional validation purposes. Here is the updated button: <button type="button" onclick="subForm()" name="del" id="delet ...

Stopping the execution of a request handling function in Express/Node: tips and tricks

I am currently running an Express server that offers some computations as web services. The computation time can vary from less than 1 second to 10 seconds. I am curious if there is a method to halt the execution of a request-handling function (which is ...

Unable to utilize jQuery's .append(data) function due to the need to use .val(append(data)) instead

I have been attempting to utilize JQuery .append(data) on success in order to change the value of an input to the appended data like this: .val(append(data)), but it doesn't seem to be working. Surprisingly, I can successfully change the value to a st ...

Tips for programmatically inserting an identifier attribute within an array of objects?

Within a simple section, I have implemented a feature where users can input movie details using a form. The values entered by the users are used to create objects, which are then pushed into an array. However, I am looking to assign a unique and dynamic ID ...

Looping through JSON keys using ng-repeat in AngularJS

I am currently working on a project where I need to populate some JSON data retrieved from the Google Tag Manager API and then send this information to the frontend which is developed in AngularJS. At the moment, I am utilizing ng-repeat on a card compone ...

The image placeholder is missing

This is my custom Results component: This is my custom Thumbnail component: `import React from "react"; const Thumbnail = ({ result }) => { return ( <div> <h1>Thumbnail</h1> </div> ); }; export default Thumb ...

Dealing with an empty req.body parameter in a NodeJS function for a Rest API using ExpressJs and sequelize

Looking for assistance with integrating ExpressJS and sequelize. I have a main function (fullaccount.js) that needs to invoke two functions ("accoun.js" and "people.js") receiving data in "fullaccount.js" for processing. However, while req.body is ready in ...

Navigating Error: net::ERR_CONNECTION while utilizing Puppeteer

I attempted to utilize a proxy from the following site: Below is my Puppeteer scraping code (deployed on Heroku), encountering an error at the .goto() method, as mentioned in the title: const preparePageForTests = async (page) => { const userAgent = & ...

Is there a way to monitor and trigger a function in jQuery when a loaded PHP file is modified?

I am currently working on a dynamic dashboard that automatically updates every few seconds to display new information fetched from a PHP file. My goal is to trigger an alert only when there is a change in the data itself, rather than just a refresh. In ord ...

Passing selection from child to parent in ReactJS

When it comes to passing data from parent components to child components, using props is a common practice. But how can data be sent back up to the parent component? I'm working on a set of dropdown menus where users can make selections: DropdownMen ...

Incorporating an image prior to the "contains" term with the help of JavaScript

Seeking assistance with the code snippet below without altering the text targeted in my "a:contains" statement. The challenge lies in determining the appropriate placement of ::before in the script provided. Link: https://jsfiddle.net/onw7aqem/ ...

The <div> element is not compatible with the <canvas> element for use

I'm having trouble inserting a <canvas> animation within a <div> element. The current code displays the animation across the entire page, but I would like to contain it within a single section, like this: <div><canvas> </can ...

What is the best way to add child elements to existing elements?

When it comes to creating elements with jQuery, most of us are familiar with the standard method: jQuery('<div/>', { id: 'foo', href: 'http://google.com', }).appendTo('#mySelector'); However, there ar ...

What steps should I take to manually split code in preact?

In my project, I am looking to manually implement code-splitting with preact. While preact already handles code splitting for routes, I want to take control of it. The scenario is that I am creating a tool where users can customize widgets on a dashboard. ...