JS failing to validate inputs

I'm facing an issue with my validation code. It doesn't seem to be working correctly.

The two things I'm trying to validate are:

  1. Check if any textfield is empty
  2. Ensure that the password field has a minimum of 8 characters

If either one of these conditions fails, an error message should be displayed. However, the error message isn't showing up when it should. Here's the snippet:

function validate() {
    if (document.getElementById("name").value == '') {
        document.getElementById("errorMsg").innerHTML = "You have forgotten to enter your name";
    }
    else if (document.getElementById("surname").value == '') {
        document.getElementById("errorMsg").innerHTML = "You have forgotten to enter your surname";
    }
    else if (document.getElementById("email").value == '') {
        document.getElementById("errorMsg").innerHTML = "You have forgotten to enter your email address";
    }
}
* {
margin: 0px;
padding: 0px;
}

#title{
    font: bold 20px Tahoma;
    color: white;
margin: 10px;
text-align: left;
    width: 80%;
}
...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Fastloader - Register for a new account</title>
    <link rel="stylesheet" href="register.css">
<script src="register.js"></script>
</head>
<body>
    <div id = "main-container">
<header id = "header">
<h1>Register for a new account<h1>
</header>
    <div id= "control-container">
    <section id ="label-container">
        <p><label>Enter your Name:</label></p>
        <p><label>Enter your Surname:</label></p>
        <p><label>Enter your Email address:</label></p>
        <p><label>Choose a strong Password:</label></p>
    </section>
    
    <status id = "element-container">
        ...
        ... // Rest of the HTML content

Answer №1

if(document.getElementById("errorMsg").value !== "Please remember to input your email address") {
    alert("You have forgotten to enter your email address"); 
}
  1. Instead of using ==, consider using !== for comparison

  2. The correct property to access text in an element is .innerText not .value

Answer №2

Here is the solution that worked for me:

function checkInput() {
    if (document.getElementById('name').value.length == 0) {
        alert("Please enter your name");
    } else if (document.getElementById("surname").value.length == 0) {
        alert("Please enter your surname");
    } else if (document.getElementById("email").value.length == 0) {
        alert("Please enter your email address");
    }
}
* {
margin: 0px;
padding: 0px;
}

#title{
    font: bold 20px Tahoma;
    color: white;
margin: 10px;
text-align: left;
    width: 80%;
}

#header{
padding: 80px;
    font: 14px Tahoma;
}

body{
width:100%;
display:-webkit-box;
-webkit-box-pack: center;
}

#main_container{
max-width: 1000px;
margin: 10px 0px;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-flex: 1;
}

#control-container{
display:-webkit-box;
-webkit-box-orient: horizontal;
}

#label-container{
-webkit-box-flex: 1;
margin: 10px;
}

p {
    font: 14px Tahoma;
margin: 20px;
    width: 350px;
    height: 30px;
}

#element-container{
width: 500px;
margin: 20px 0px;
display: -webkit-box;
-webkit-box-orient: vertical;
}

#name{
    font: 14px Tahoma;
margin: 10px;
    width: 350px;
    height: 30px;
}

#surname{
    font: 14px Tahoma;
    margin: 10px;
    width: 350px;
    height: 30px;
}

#email{
    font: 14px Tahoma;
    margin: 10px;
    width: 350px;
    height: 30px;
}

#password{
    font: 14px Tahoma;
    margin: 10px;
    width: 350px;
    height: 30px;
}

input[type="text"]:focus{
    outline: none;
    box-shadow: 0px 0px 5px #7f0000;
    border:1px solid #b20000;
}

input[type="text"]:hover{
    border: 1px solid #999;
}

input[type="text"]:focus:hover{
    outline: none;
    box-shadow: 0px 0px 5px #7f0000;
    border:1px solid #b20000;
}  

input[type="password"]:focus{
    outline: none;
    box-shadow: 0px 0px 5px #7f0000;
    border:1px solid #b20000;
}

input[type="password"]:hover{
    border: 1px solid #999;
    border-radius: 0px;
}

input[type="password"]:focus:hover{
    outline: none;
    box-shadow: 0px 0px 5px #7f0000;
    border:1px solid #b20000;
    border-radius:0;
}  

#register{
    font: 14px Tahoma;
margin: 20px;
    text-align: center;
}

#btnRegister {
    width: 100px;
    height: 30px;
    margin: 20px;
    text-align: center;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Fastloader - Register for a new account</title>
    <link rel="stylesheet" href="register.css">
<script src="register.js"></script>
</head>
<body>
    <div id = "main-container">
<header id = "header">
<h1>Register for a new account<h1>
</header>
    <div id= "control-container">
    <section id ="label-container">
        <p><label>Enter your Name:</label></p>
        <p><label>Enter your Surname:</label></p>
        <p><label>Enter your Email address:</label></p>
        <p><label>Choose a strong Password:</label></p>
    </section>
    
    <section id = "element-container">
        <div id = "name_container">            
            <input name="Name" type="text" id="name"/>
        </div>
        <div id = "surname_container">
            <input name="Surname" type="text" id="surname"/>
        </div>
        <div id = "email_container">
            <input name="Email" type="text" id="email" />
        </div>
        <div id = "password_container">
            <input name="Password" type="password" id = "password"/>
        </div>
    </section>
    </div>
        <footer id = "register">
        <div id = "agreement">
            <label>I have read the Terms and Conditions:</label>
            <input name="agree" type="checkbox" id="agree" />
        </div>
            <div id = "error">
            <p><label id = "errorMsg"></label></p>
            </div>
        <div id = "button">
            <input type = "button" 
                   id="btnRegister" 
                   value = "Register" 
                   onclick="checkInput();"/>
        </div>
        </footer>
    </div>
</body>
</html>

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

What is the reason behind the reversal of meaning for the exclamation mark in CSS compared to its usage in C-based languages?

Take JavaScript for instance, where !important signifies 'not important'. But in CSS, it indicates that something is actually important. Do you know of any other programming languages besides CSS that use an exclamation mark to show affirmation ...

Is it possible to create a Footer with a 100% width in CSS?

I have a simple HTML page with all elements contained within a mainWrapper div and secondWrapper div. Everything is currently sized to 960px, including the pageHeader, pageContent, and pageFooter. However, I need to keep everything at 960px except for th ...

Arrange the selection options by price using jQuery

Sorting options by price is my goal, but despite trying various codes, I have not been successful! This is the original structure: <select id="product-list"> <option>product 1- [2$]</option> <option>product 2- [4$]< ...

Managing Data Forms in JavaScript to Handle Large Amounts of Information

As I dive into learning JavaScript with the goal of creating a large form that remains completely local without involving a web server, I am faced with some challenges. I have extensive experience with PHP, but JavaScript is uncharted territory for me. T ...

"Creating Eye-Catching CSS Animation Effects with Dynamic Initial States

I am looking to understand how I can seamlessly transition from a hover-triggered animation to an exit-hover animation, regardless of where the hover animation is in progress. Currently, if I exit hover too quickly, the animation jumps back to its starting ...

issues with adding class to div element

I have a div section that contains various movie items and overlay elements. <div class="overlay"> <a title="yes" href="#"><div class="yes"></div></a> <a title="no" href="#"><div class="no"></div>< ...

Can you explain the exact purpose of npm install --legacy-peer-deps? When would it be advisable to use this command, and what are some potential scenarios where it

Encountered a new error today: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1cfc4d9d5d5d6c8cfe1918f908f91">[em ...

Trouble with Updating InnerHTML

xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", "myurlhere.php", true ); xmlHttp.send(); var display = document.getElementById("display"); display.innerHTML = xmlHttp.response; This snippet of code is part of a function triggered by a button click. ...

There are errors occurring in the getter I created within the vuex store.js file

Currently utilizing vuejs, vuex, and vuetify. Within this project there are 3 files in play and I will share the key sections here. The main objective is to showcase data associated with the route parameter. Despite my attempts in Product.vue as shown bel ...

The specific characteristics of an item in the programming language Javascript

Imagine having 5 unique buttons on a webpage. Each button, when clicked by the user, triggers a JavaScript function that manipulates the button's state using its individual this.state variable. The challenge lies in creating distinct variables for eac ...

The scrolling function in CSS is malfunctioning

I encountered a scroll-x issue in CSS Here is the HTML code snippet: <div id=main_user_chat_tab_div class="chat-container_div" style="border:4px solid #F00;"> <div id="chat_box_win" class="chat_box_win" style="position:relative;"></div ...

Error in Next.js: The element type is not valid. Please make sure it is either a string (for built-in components) or a class/function (for composite components) and not undefined

I've encountered an issue while working on my Next.js project where I am trying to import the Layout component into my _app.js file. The error message I received is as follows: Error: Element type is invalid: expected a string (for built-in componen ...

The declaration file for the module 'bootstrap/dist/js/bootstrap' could not be located

Currently, I am developing a Next.js application and have integrated Bootstrap for styling. However, I am encountering an error when trying to import the bootstrap.bundle.js file. I am facing the following error message: Could not find a declaration file f ...

Ways to customize a bot's status based on the time of day

I'm currently working on enhancing my discord bot by having its status change every hour for a more dynamic user experience. However, I'm facing challenges with JavaScript dates. Can anyone provide some guidance? Below is the snippet of code I ha ...

Resolve Bootstrap 4 responsive table header alignment glitch

Utilizing the d-none and d-md-block classes on a responsive table to hide certain columns at smaller screen sizes has been successful overall. However, there is one issue - the hidden columns seem to be slightly misaligned with the rest of the table. Despi ...

Tips for keeping a Bootstrap div fixed at the top of the viewport

I have a webpage built with Bootstrap 5 that incorporates vertical navigation tabs. The issue I am facing is that, particularly on larger screens, the page tends to scroll up and down based on the content displayed in the tabs. My goal is to ensure that t ...

I am keen on eliminating the lower margin of the PIXI application

Exploring the possibilities of PIXI.js, I am working on creating a new application. However, upon adding the PIXI application to the DOM, I noticed an unwanted margin at the bottom. Here is an image illustrating the issue. Is there a way to remove this bo ...

Encountering undefined JavaScript functions when called from HTML

I had most of these functions working perfectly, but after restarting my program, I'm now encountering issues with undefined functions in Chrome. I can't pinpoint the exact problem, and even though I've checked through Eclipse, I still can&a ...

How can we show a div element when hovering over another element using css-in-js?

Is there a way to use material ui withStyles component in order to show information only on hover for a specific div? ...

The unique and personalized accordion panel is experiencing technical difficulties

Here is the accordion script I am using: $(document).ready(function(){ $(function(){ // Accordion Panels $(".accordion span").hide(); $(".accordion li").click(function(){ $(this).next(".pane").slideToggle("fast").siblings(".pane:visible").sl ...