Tips for incorporating error messages based on specific errors in HTML

In the current setup, a common error message is displayed for all errors. However, I want to customize the error messages based on the specific type of error. For example, if the password is invalid, it should display "invalid password", and for an invalid username, it should display "invalid username."

html {
    height: 100%;
}

body {
    height: 100%;
    margin: 0;
    font-family: Arial, Helvetica, sans-serif;
    display: grid;
    justify-items: center; 
    align-items: center;
    background-color: #d39090;
}

#main-holder {
    width: 50%;
    height: 70%;
    display: grid;
    justify-items: center; 
    align-items: center;
    background-color: white;
    border-radius: 7px;
    box-shadow: 0px 0px 5px 2px black;
}

#signup-error-msg-holder {
    width: 100%; 
    height: 100%;
    display: grid;
    justify-items: center; 
    align-items: center;
}

#signup-error-msg {
    width: 23%;
    text-align: center;
    margin: 0;
    padding: 5px; 
    font-size: 16px;
    font-weight: bold;
    color: #8a0000;
    border: 1px solid #8a0000;
    background-color: #e58f8f;
    opacity: 0;
}

#error-msg-second-line {
    display: block;
}

#signup-form {
    align-self: flex-start;
    display: grid;
    justify-items: center; 
    align-items: center;
}

.signup-form-field::placeholder {
    color: #2e4136;
}

.signup-form-field {
    border: none; 
    border-bottom: 1px solid #755ddf;
    margin-bottom: 10px;
    border-radius: 3px;
    outline: none;
    padding: 0px 0px 5px 5px;
}

#signup-form-submit {
    width: 100%;
    margin-top: 20px;
    padding: 10px;
    border: none; 
    border-radius: 5px;
    color: white;
    font-weight: bold;
    background-color: #43509b;
    cursor: pointer;
    outline: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sign Up Page</title>
    <link rel="stylesheet" href="interlog.css">

</head>

<body>
    <main id="main-holder">
        <h1 id="signup-header"><b>Sign Up</b></h1>

        <div id="signup-error-msg-holder">
            <p id="signup-error-msg">Invalid username <span id="error-msg-second-line">and/or password</span></p>
        </div>

        <form id="signup-form">
            <input type="text" name="username" id="username-field" class="signup-form-field" placeholder="Username">
            <input type="password" name="password" id="password-field" class="signup-form-field" placeholder="Password">
            <input type="submit" value="submit" id="signup-form-submit">
        </form>

    </main>

    <script>
        const signupForm = document.getElementById("signup-form");
        const signupButton = document.getElementById("signup-form-submit");
        const signupErrorMsg = document.getElementById("signup-error-msg");

        signupButton.addEventListener("click", (e) => {
            e.preventDefault();
            const username = signupForm.username.value;
            const password = signupForm.password.value;

            if (username === "admin" && password === "password") {
                alert("You have successfully logged in.");
                location.reload();
            } else {
                signupErrorMsg.style.opacity = 1;
            }
        })
    </script>

</body>

</html>

I'm looking for guidance on how to achieve this customization. I attempted to add another message at signup-error-msg-holder and made changes in the JavaScript, but both messages were displaying simultaneously.

`<div id="signup-error-msg-holder">
        <p id="signup-error-msg1">Invalid password</p>
    </div>
    <div id="signup-error-msg-holder">
        <p id="signup-error-msg2">Invalid username </p>
    </div>

`

const signupErrorMsg1 = document.getElementById("signup-error-msg1");
    const signupErrorMsg2 = document.getElementById("signup-error-msg2");

    signupButton.addEventListener("click", (e) => {
        e.preventDefault();
        const username = signupForm.username.value;
        const password = signupForm.password.value;

        if (username === "admin" && password === "password") {
            alert("You have successfully logged in.");
            location.reload();
        } else if (username === "admin" && password !== "password") {
            signupErrorMsg1.style.opacity = 1;
        } else if (username !== "admin" && password === "password") {
            signupErrorMsg2.style.opacity = 1;
        }
    })

`

Your assistance would be greatly appreciated.

Answer №1

Testing each item and storing errors in an array. If the array is empty, then all tests have passed

const signupForm = document.getElementById("signup-form");
const signupButton = document.getElementById("signup-form-submit");
const signupErrorMsg = document.getElementById("signup-error-msg");

signupButton.addEventListener("click", (e) => {
  e.preventDefault();
  const username = signupForm.username.value;
  const password = signupForm.password.value;
  const msg = []
  if (username !== "admin") msg.push("username")
  if (password !== "password") msg.push("password")
  if (msg.length === 0) {
    alert("You have successfully logged in.");
    location.reload();
    return;
  }
  signupErrorMsg.textContent = "Invalid " + msg.join(" and ");
  signupErrorMsg.style.opacity = 1;

})
html {
  height: 100%;
}

body {
  height: 100%;
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
  display: grid;
  justify-items: center;
  align-items: center;
  background-color: #d39090;
}

#main-holder {
  width: 50%;
  height: 70%;
  display: grid;
  justify-items: center;
  align-items: center;
  background-color: white;
  border-radius: 7px;
  box-shadow: 0px 0px 5px 2px black;
}

#signup-error-msg-holder {
  width: 100%;
  height: 100%;
  display: grid;
  justify-items: center;
  align-items: center;
}

#signup-error-msg {
  width: 23%;
  text-align: center;
  margin: 0;
  padding: 5px;
  font-size: 16px;
  font-weight: bold;
  color: #8a0000;
  border: 1px solid #8a0000;
  background-color: #e58f8f;
  opacity: 0;
}

#error-msg-second-line {
  display: block;
}

#signup-form {
  align-self: flex-start;
  display: grid;
  justify-items: center;
  align-items: center;
}

.signup-form-field::placeholder {
  color: #2e4136;
}

.signup-form-field {
  border: none;
  border-bottom: 1px solid #755ddf;
  margin-bottom: 10px;
  border-radius: 3px;
  outline: none;
  padding: 0px 0px 5px 5px;
}

#signup-form-submit {
  width: 100%;
  margin-top: 20px;
  padding: 10px;
  border: none;
  border-radius: 5px;
  color: white;
  font-weight: bold;
  background-color: #43509b;
  cursor: pointer;
  outline: none;
}
<main id="main-holder">
  <h1 id="signup-header"><b>Sign Up</b></h1>

  <div id="signup-error-msg-holder">
    <p id="signup-error-msg"></p>
  </div>

  <form id="signup-form">
    <input type="text" name="username" id="username-field" class="signup-form-field" placeholder="Username">
    <input type="password" name="password" id="password-field" class="signup-form-field" placeholder="Password">
    <input type="submit" value="submit" id="signup-form-submit">
  </form>

</main>

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 best way to retrieve information from a data set?

After borrowing some basic HTML, CSS, and JavaScript code from CodePen, I ran into an issue while attempting to convert it to React. The error message says that it cannot read properties of null (specifically 'dataset'). Here is the JavaScript c ...

Synchronize numerous PouchDB databases with a single CouchDB database

After reading the PouchDB documentation, I learned that sync occurs between a local database and a remote CouchDB database. Currently, I am working on developing a native application that includes a unique local database for each user (multiple databases) ...

CSS for leaving white space at the end of one third of a container

Currently developing a website and facing an issue with the layout: I am trying to create 3 columns of equal height with each column taking up one-third of the width. However, there seems to be a small white gap on the right side of the last column. Here ...

Elevation in design ui component

I am having an issue with the height of a theme-ui component I embedded. Even though the console shows it correctly, it is displaying at 100% height. <Embed src={url} sx={{width: '800px', height: '400px'}}/> This embed is contain ...

The ultimate guide to personalizing group titles in Angular UI-Select

Is there a way in Angular ui-select to customize the group label? I want to make it larger than the selection items as shown in the image below. https://i.stack.imgur.com/ofcak.png The list is currently grouped by country, but how can I adjust the size o ...

Retrieve an array of information from a firestore database query

I am encountering an issue while trying to retrieve information about all users who are friends of a specific user. I have attempted to gather the data by pushing it to an array and then returning it as a single JSON array. However, it seems that the dat ...

Having trouble properly implementing variable updates when creating a multi-theme website

I have a Next.js app and a globals file containing all the themes: body { margin: 0; font-family: Inconsolata, monospace; background-color: var(--bg-color); } :root { --bg-color: #262a33; --main-color: #43ffaf; --sub-color: #526777; --sub-al ...

WebAPI provides a similar functionality to an array in JavaScript through the use of IQueryable

I have a WebAPI method that returns an IQueryable of a 'complex' object in the following format: [Route("api/INV_API/deptSelect")] public IQueryable<DEPTNAME_DESCR> GetDistinctDeptSelect([FromUri] string q) { if (q != null) ...

What is the best way to incorporate a subcategory within a string and separate them by commas using Vue.js?

Is it possible to post subcategories in the following format now? Here is the current result: subcategory[] : Healthcare subcategory[] : education However, I would like to have them as a string separated by commas. This is my HTML code: <div id="sub ...

Recording the $index value of dynamically included inputs

Check out my Plunker demo: http://plnkr.co/edit/sm3r4waKZkhd6Wvh0JdB?p=preview I have a dynamic set of form elements that users can add and remove. I am looking to include an 'id' property for each object in the form elements, corresponding to ...

Chrome not handling text wrapping within table cells properly

I'm facing an issue with a table I created using the bootstrap stylesheet. For some reason, the cells are not wrapping correctly in Chrome, although they display perfectly fine in IE and Firefox. You can check it out here: <form action="todos" m ...

Is there a way to eliminate the header and footer from a Flutter WebView?

Here is the code snippet I tried to implement: I found a video tutorial by Joannes Mike on YouTube demonstrating how to remove the header and footer in Flutter WebView. However, it seems that Flutter has updated their library and the functions no longer w ...

Managing data in Vuex by updating it from a child component using $emit

I'm currently working on a Vue app that has the capability to randomize a title and subtitle or allow users to manually edit these values using a custom input component. The challenge I'm facing is updating the parent component and state to refle ...

Concealing HTML content with a modal overlay

There are security concerns with my authentication overlay modal, especially for users familiar with CSS and HTML. Is there a way to hide the HTML behind the modal so it doesn't appear in the page source? The code below is just an example of a modal ...

The SharedArrayBuffer does not exist in this context

A new library, react-canvas, has been causing some trouble for me. Lately, an error message keeps appearing with the <p> tag in the canvas area where it should be displayed on browsers like Chrome. The framework I'm using is nextjs, and I&apos ...

When a user clicks on a specific element's id, the image will rotate accordingly

When the elements in ul are clicked, the image rotates. The default position of the image is already rotated by a certain number of degrees, and on each click, it rotates to the desired value. This was achieved using the following code: $("#objRotates"). ...

Restoring hover functionality after resetting color using jQuery - tips and tricks

My jQuery code is working well, but I am facing one issue. After clicking on my infocontent menu, the hover effect on h1 is no longer working. How can I bring back the hover function? Here is the HTML: <div class="infocontent"><h1>What?</h ...

Determine if a point within a shape on a map is contained within another shape using Leaf

I have extracted two sets of polygon coordinates from a leaflet geoJSON map. These are the parent and child coordinates: var parentCoordinates=[ [ 32.05898221582174, -28.31004731142091 ], [ 32.05898221582174, -2 ...

Managing different user types in HTML5

I'm in the process of creating an application that interacts with a service and performs various tasks based on user permissions. After doing some research, I discovered that Kinvey offers a solution that is similar to what I need, but I'm not c ...

Having trouble embedding Hangouts button in HTML template using script tags

When I include a Hangouts button on my index page, it is visible and functional as expected: <body ng-app="sampleApp" ng-controller="MainCtrl"> <div class="row"> <div class="col-md-12 m-body"> <div class="m ...