Issue with printing error messages for JavaScript form validation

I have implemented the following code for a form to handle validation and display errors below the fields when they occur:

<!DOCTYPE html>
<html>
<head>
 <style type="text/css">

.errorcss {
   background-color: yellow;
   color:red;
}
</style>

<script type="text/javascript">
error = " ";

function isBlank(s) {

  var len = s.length;
  var i;
  for (i = 0; i < len; ++i) {
    if (s.charAt(i) != " ") return false;
  }
  return true;
}

function validate(fieldName, fieldValue) {

  if (isBlank(fieldValue)) {
     error = fieldName + " cannot be left blank.";
     alert(fieldName + " cannot be left blank.");
     return false;
  }
  return true;
}

function validatePass(passwordValue, confirmPasswordValue) {

  if (passwordValue !== confirmPasswordValue) {
     alert("Password and Confirm Password do not match");
     return false;
  }
  return true;
}


function validateForm() {

  if (!validate("The last name field", document.contest.last.value))
     return false;
  if (!validate("The email field", document.contest.email.value))
     return false;
  if (!validate("The password field", document.contest.pass.value))
     return false;

  if (!validatePass(document.contest.pass.value, document.contest.repass.value))
     return false;
  if (!validate("The description field", document.contest.desc.value))
     return false;
}

</script>
</head>

<body>
<form name="contest" onSubmit = "return validateForm()" method="GET">
<h2 align="center">Sign Up Form</h2>
<p>
*Last Name:<input type="text" name="last" size="16">
First Name:<input type="text" name="first" size="12">
Middle Initial:<input type="text" name="initial" size="2">
</p>
<div class="errorcss">
   <script type="text/javascript">document.write(error);</script>
</div>
<p>
*E-mail Address:<input type="email" name="email">
*Password:<input type="password" size="10" name="pass">
*Confirm Password:<input type="password" size = "10" name="repass">
</p>
<p>
In 50 words or less, describe yourself:
</p>
<textarea name="desc" ROWS="5" COLS="40"></textarea>
<p>
Submit your form:<input type="SUBMIT" value="Submit my form">
</p>
</form>
</body>
</html>

My current issue is that I want the "no last name" error to be displayed in the div with errorcss class, but it is not displaying. Additionally, I am exploring ways to display all errors when they occur using JavaScript and CSS.

Answer №1

In order to fix the error div, I made several changes. I added 15 semicolons, removed the script inside the error div, and assigned the error div an id ('errordiv'). Additionally, I included the following code snippet:

document.getElementById('errordiv').innerText=error;

This code is placed within the function validateForm();.

Resulting HTML Code:

<!DOCTYPE html>
<html >
<head >
    <style type="text/css" >

        .errorcss {
            background-color : yellow;
            color            : red;
        }
    </style >

    <script type="text/javascript" >
        error = " ";

        function isBlank( s )
        {

            var len = s.length;
            var i;
            for ( i = 0; i < len; ++i ) {
                if ( s.charAt( i ) != " " ) return false;
            }
            return true;
        }

        function validate( fieldName, fieldValue )
        {

            if ( isBlank( fieldValue ) ) {
                error = fieldName + " cannot be left blank.";
                alert( fieldName + " cannot be left blank." );
                return false;
            }
            return true;
        }

        function validatePass( passwordValue, confirmPasswordValue )
        {

            if ( passwordValue !== confirmPasswordValue ) {
                alert( "Password and Confirm Password do not match" );
                return false;
            }
            return true;
        }

        function validateForm()
        {

            if ( !validate( "The last name field", document.contest.last.value ) ) {
                document.getElementById( 'errordiv' ).innerText = error;
                return false;
            }
            if ( !validate( "The email field", document.contest.email.value ) ) {
                return false;
            }
            if ( !validate( "The password field", document.contest.pass.value ) ) {
                return false;
            }

            if ( !validatePass( document.contest.pass.value, document.contest.repass.value ) ) {
                return false;
            }
            if ( !validate( "The description field", document.contest.desc.value ) ) {
                return false;
            }
        }

    </script >
</head >

<body >
    <form name="contest" onSubmit="return validateForm()" method="GET" >
        <h2 align="center" >Sign Up Form</h2 >

        <p >
            *Last Name:<input type="text" name="last" size="16" > First Name:<input type="text" name="first" size="12" > Middle Initial:<input type="text" name="initial" size="2" >
        </p >

        <div class="errorcss" id="errordiv" >

        </div >
        <p >
            *E-mail Address:<input type="email" name="email" > *Password:<input type="password" size="10" name="pass" > *Confirm Password:<input type="password" size="10" name="repass" >
        </p >

        <p >
            In 50 words or less, describe yourself:
        </p >
        <textarea name="desc" ROWS="5" COLS="40" ></textarea >

        <p >
            Submit your form:<input type="SUBMIT" value="Submit my form" >
        </p >
    </form >
</body >

Answer №2

There are numerous issues to address, one of which is:

  <div class="errorcss">
    <script type="text/javascript">
      document.write(error);//code fails on page load
    </script>
  </div>

Take a look at this:

function checkIfEmpty(s) {
  return 0 === s.replace(/\s/g, '').length;
}

function verifyInput(fieldName, fieldValue) {
  if (checkIfEmpty(fieldValue)) {
    alert(fieldName + " cannot be left blank.")
    return false
  }
  return true
}

function validatePassword(passwordValue, confirmPasswordValue) {

  if (passwordValue !== confirmPasswordValue) {
    alert("Password and Confirm Password do not match")
    return false
  }
  return true
}


function validateRegistrationForm() {
  if (!verifyInput("The last name field", document.contest.last.value))
    return false
  if (!verifyInput("The email field", document.contest.email.value))
    return false
  if (!verifyInput("The password field", document.contest.pass.value))
    return false

  if (!validatePassword(document.contest.pass.value, document.contest.repass.value))
    return false
  if (!verifyInput("The description field", document.contest.desc.value))
    return false
}
<form name="contest" onSubmit="return validateRegistrationForm()" method="GET">
  <h2 align="center">Sign Up Form</h2>
  *Last Name:
  <input type="text" name="last" size="16">
  <br/>First Name:
  <input type="text" name="first" size="12">
  <br/>Middle Initial:
  <input type="text" name="initial" size="2">
  <br/>*E-mail Address:
  <input type="email" name="email">
  <br/>*Password:
  <input type="password" size="10" name="pass">
  <br/>*Confirm Password:
  <input type="password" size="10" name="repass">
  <br/>In 50 words or less, describe yourself:
  <textarea name="desc" ROWS="5" COLS="40"></textarea>
  <br/>Submit your form:
  <input type="SUBMIT" value="Submit my form">
</form>

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 IDs and classes of HTML elements

I have two different implementations of a livechat script. On my sandbox site, the livechat is fixed to the bottom right of the page and scrolls with the window. However, on my live site (where this specific code comes from), it is attached to the footer. ...

Leveraging the power of ES6 syntax in Node scripts with Babel

My npm CLI tool utilizes ES6 syntax from BabelJS, specifically arrow functions. Within the entry point of my tool, I'm using the following require: require('babel-core/register'); var program = require('./modules/program.js'); I ...

What is the best way to create a React component that renders a class component as a functional component?

My Objective: At the moment, I am in the process of developing an AuthUserRole HOC component to manage user roles like Manager and Employee. However, I encountered a tutorial that uses a functional component to return a class component as referenced here. ...

AdjustIframeHeightOnLoad is undefined. Please define it before use

I've noticed that a few of my website pages are loading very slowly. After checking Google inspect (console), it seems like the issue is caused by this error: Uncaught ReferenceError: AdjustIframeHeightOnLoad is not defined. This specific piece of co ...

Creating a seamless full-page grid layout with CSS to eliminate the need for scrolling

My goal is to have 20 items on the grid of this page, each taking up full width and height with a fluid layout. Currently, I have successfully set up the page with 20 items spanning full width in a fluid design. However, the content of the grid is being p ...

The submission of an Angular form results in errors such as being unavailable or

After building a registration page component in Angular and following tutorials, I encountered a frustrating bug. When pressing the submit button on the form, the console would display "undefined" when attempting to access the NgForm's value. However, ...

How to extract the root website URL using JavaScript for redirection purposes

I am facing an issue with redirecting to the Login page from every page on my website after session timeout. I attempted to set the window location to the login page using the following code: var ParentUrl = encodeURIComponent(window.parent.location.href) ...

In Chrome, the height of 100% is not functioning properly within the <div> element

I've been struggling with a problem that I've searched the internet for solutions to, but haven't been able to resolve. The issue revolves around an iframe containing a page that loads specific CSS rules. html, body { position: relative; he ...

What is the best way to utilize the ajax factory method in order to establish a $scoped variable?

One issue I frequently encounter in my controllers is a repetitive piece of code: // Get first product from list Product.get_details( id ) .success(function ( data ) { // Setup product details $scope.active_product = data; }); To avoid this ...

Restrict HTML Elements Based on Their Size

I have a text file with a substantial amount of content that I need to display in an HTML format. The challenge is that I only want to show a portion of the text on the screen, but I am unsure of the exact amount that needs to be displayed. What I do know ...

Assign a value to ng-model using JavaScript

Encountering an issue while working with JavaScript in AngularJS. There is a text field identified by id="longitude". <input type="text" data-ng-model="newwarehouse.longtitude" id="longitude"/> The value of this field is being set using JavaScript. ...

Puppeteer causes Express to stop listening to incoming requests

As I work on developing a straightforward API that utilizes Puppeteer to execute actions, I encounter an issue where my Express app stops listening once Puppeteer is launched. Below is the script in question: const Apify = require('apify'); cons ...

Guide to removing a Firebase Storage directory using a Firebase Cloud Function?

I'm having trouble finding the deleteFiles() method and the DeleteFilesOptions argument in the Firebase API reference. My IDE is indicating that this method requires an optional argument, but I can't seem to locate any information on this type. I ...

Different types of video formats used for html5 video players

Looking for some guidance here. I'm currently in the process of developing a website that allows users to upload their own videos. For the video player, I've opted for the HTML5 player by . My main concern is ensuring that the HTML5 player can on ...

What is the best method for utilizing the CSS :target selector in order to generate a versatile modal box?

I am looking for a way to display my vast collection of proverbs from an endangered language without overcrowding the page. I have implemented a modal box solution using CSS :target selector, which expands a hidden div element when clicked on. However, I n ...

Angular Resolution Verification

I'm currently working on making HTTP calls in Angular and I want to trigger a different service function if an error occurs. The problem is, no matter what the original service call function returns, the promise always ends up being "undefined". Here& ...

What is the best way to upgrade to a specific version of a child dependency within a module?

npm version: 7.24.2 Looking for assistance on updating a child dependency. The dependency in question is: vue-tel-input This dependency relies on libphonenumber-js with version ^1.9.6 I am aiming to update libphonenumber-js to version ^1.10.12. I have ...

Revive your Chart JS visualization with interactive re-animation via onclick action!

I've been exploring Chart.js and trying to achieve something simple, but I'm having trouble. I just want the chart to re-animate when clicking on a button, but I can't seem to make it work. I attempted to attach chart.update to the onclick e ...

jQuery for Dynamic CSS Class

Is there a way to apply a different style to a link upon page load with jQuery? I would like the link to appear highlighted when the user navigates to a specific page, such as clicking on the About Us menu item. I want to use jQuery to achieve this effect. ...

Is it possible to manipulate content using jQuery?

I need help figuring out how to update the content within a span tag when a user clicks on a button. The specific span tag I am trying to target has a class called fa_button_id_counter and an id that corresponds to the post id. Despite my efforts, I haven& ...