Weak Password Alert

After spending hours writing code for form validation and password strength checking, I encountered a roadblock. The form validates successfully, but the password strength indicator is not updating as expected. Despite double-checking the logic in my code snippet, the color of the bar remains unchanged when typing strong or weak passwords.

<!DOCTYPE html>
<html>
<head>

<style>
  .strength-bar {
        width: 100%;
        height: 30px;
        background-color: lightgrey;
        border: 1px solid black;
        margin: 10px 0;
      }

      /* CSS for the strength meter */
      .strength-meter {
        height: 100%;
        background-color: green;
        transition: width 0.5s;
      }

      /* CSS for a weak password */
      .weak {
        width: 33%;
        background-color: red;
      }

      /* CSS for a strong password */
      .strong {
        width: 66%;
        background-color: orange;
      }
</style>



<script>
function validateForm() {
  var password = document.forms["myForm"]["password"].value;
  
  // Check if password contains at least one lowercase letter
  if (!password.match(/[a-z]/)) {
    alert("Error: Password must contain at least one lowercase letter!");
    return false;
  }
  
  // Check if password contains at least one uppercase letter
  if (!password.match(/[A-Z]/)) {
    alert("Error: Password must contain at least one uppercase letter!");
    return false;
  }
  
  // Check if password contains at least one number
  if (!password.match(/[0-9]/)) {
    alert("Error: Password must contain at least one number!");
    return false;
  }
  
  // Check if password is at least 8 characters long
  if (password.length < 8) {
    alert("Error: Password must be at least 8 characters long!");
    return false;
  }
  
  // If all checks pass, submit the form
  return true;
}


</script>
</head>
<body>

<form name="myForm" action="nextpage.html" onsubmit="return validateForm();" oninput="checkPassword();"  method="post">
  Name: <input type="text" name="name"><br>
  Password: <input type="password" name="password"><br>
  <div class="strength-bar">
    <div id="strength-meter" class="strength-meter"></div>
  </div>
  <br>
  <input type="submit" value="Submit">
</form> 
<script>
    // Function to check the password strength
function checkPassword() {
        // Get the password from the input field
        var password = document.getElementById("password").value;

        // Check if the password meets the requirements
        var hasUppercase = /[A-Z]/.test(password);
        var hasLowercase = /[a-z]/.test(password);
        var hasNumber = /\d/.test(password);
        var has8Chars = password.length >= 8;

        // Set the strength meter width and color
        var strengthMeter = document.getElementById("strength-meter");
        if (hasUppercase && hasLowercase && hasNumber && has8Chars) {
          // Strong password
          strengthMeter.style.width = "66%";
          strengthMeter.classList.remove("weak");
          strengthMeter.classList.add("strong");
        } else {
          // Weak password
          strengthMeter.style.width = "33%";
          strengthMeter.classList.remove("strong");
          strengthMeter.classList.add("weak");
        }
      }
</script>
</body>
</html>

I've reviewed the logic numerous times, yet the issue persists. It's puzzling why the color isn't changing when entering different types of passwords, only showing the green bar.

Answer №1

It appears that the issue lies in your code only updating the password strength meter when the function checkPassword is triggered, and this function is never actually called anywhere in your code. To ensure real-time updates to the password strength meter, you must invoke the function whenever the user inputs something in the password field.

To achieve this, you can attach an onkeyup event listener to the password input field and execute the checkPassword function within this event listener. Here's an example:

<!-- Password input -->
<input type="password" id="password" onkeyup="checkPassword()">

<!-- Password strength -->
<div id="strength-meter" class="strength-meter"></div>

This setup will trigger the checkPassword function every time a key is released while the password input field is active, ensuring that the password strength meter reflects real-time changes as the user types their password.

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

Problem with Postman's form-data functionality

I am facing an issue with using Postman and body->form-data. The code works perfectly fine when I use express.json parser with body->raw and body->urlencoded, but for some reason it does not work with formData. https://i.sstatic.net/6DuCd.png ht ...

Why is the radio button not chosen in the ns-popover popup? The radio button is only selected in the popup of the last column

In my Angular controller, I am trying to set the radio model but it is only appearing in the last column popup of the table. The ns-popover is displayed when clicking on a table column. Here is the Angular Code: var app = angular.module('app', ...

Email link spilling out from within image hyperlink

My website, located at , is experiencing an issue where the small envelope icon's mailto link is overflowing to the whole box instead of just the image itself. If anyone could provide assistance in resolving this issue, it would be greatly appreciate ...

What is the process for obtaining a Facebook page ID using the Facebook page name?

Can someone please explain the process of obtaining a Facebook page ID from the Facebook page name? I noticed on this website that it displays the number of likes based on the Facebook page name. If anyone has any insight on how to achieve this, I would ...

How can unicode (%u2014) be handled in JavaScript or C#/.NET?

While browsing through the vast expanse of the internet (specifically on a review site like Rotten Tomatoes), I stumbled upon %u2014. This particular string reminded me of something I once encountered in JavaScript. Although I can't quite recall if it ...

When using IE6, images may momentarily appear stretched when set to height:auto

I have set the height to auto, however I am observing that small thumbnail images are being momentarily stretched vertically in Internet Explorer 6 before adjusting to their correct height. It is worth mentioning that the image tag in the HTML appears as ...

Tips on ensuring a div stays on the same line

I am facing an issue with a div containing two inner divs, which is currently structured as follows: https://i.sstatic.net/jy8s6.png However, when the second inner div has more content, it appears like this: https://i.sstatic.net/ezvyU.png Is there a w ...

Deleting a folder using npm prior to the build process

Can someone help me with this issue? I have the following script: "build": "rimraf dist webpack --progress --config webpack/prod.js", However, instead of just removing the 'dist' folder, it is removing all files inside the 'webpack' fol ...

Using VueJS to apply filters to an object causes a decrease in my application's performance

Recently, I've been working on implementing a filter for a search bar. However, I've noticed that whenever I input something into the search bar, there is a noticeable delay as it loads the entries. I'm not sure if this issue is related to ...

What causes the error "property does not exist on type" when using object destructuring?

Why am I encountering an error in TypeScript when using Object destructuring? The JavaScript code executes without any issues, but TypeScript is showing errors. fn error: This expression is not callable. Not all elements of type '(() => void) | ...

Struggling to create HTML divs with CSS styling

Currently working on creating a 768x240 window design. An example of what I have so far: <div class="global-tab"> <div class="image" src="link"></div> <div class="class1">{{details.name}}</div> <div class="class2" ...

Ways to target only the adjacent div

My goal is to target only the next div with the class name indented. Each indented div should have the same id as the <li> element right before it. Currently, I want each div with the class name indented to have the id of the previous <li>. He ...

Building a website using Bootstrap: A step-by-step guide

Wondering how I can incorporate all the cool Bootstrap components into a webpage. Is there a tool that offers live preview? Back in the day (web 1.0), Dreamweaver was my go-to for creating HTML and basic CSS, but what are some current tools where I can si ...

Understanding the Typescript Type for a JSON Schema Object

When working with JSON-schema objects in typescript, is there a specific type that should be associated with them? I currently have a method within my class that validates whether its members adhere to the dynamic json schema schema. This is how I am doing ...

Navigating the Angular Element: A Guide to Clicking Buttons within Modal-Dialogs Using Protractor

I am currently creating an automation test for an angular application using the protractor framework. Test scenario: Click on the "Create PDF Report" button A modal-dialog window will appear Click on the "Run Report Now" button within the modal-d ...

Tips for transfering variables from an electron application to the backend of an Angular project

My goal is to develop a website and desktop application using the same code base. However, due to some minor differences between the two platforms, I need a way for my Angular app to distinguish whether it has been called from the web or from Electron. I& ...

What is the best way to enable a service to retrieve variables from the Controller?

My controller has variables declared on the $scope and two arrays that hold objects: one for available groups and the other for groups the user is already a part of. The addUserToGroups() function sends a call to the server to add the user to the selected ...

Tips for displaying Facebook comments with JavaScript

Can anyone help me figure out how to customize the data-href for Facebook comments using JavaScript (jQuery)? I tried incorporating the code below, but it's not displaying anything in the div col2. $("#col2").html( id+"<div class='fb-comm ...

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

Leveraging the Recyclability Aspect of a ReactJS Modal

Looking for a way to make a modal dynamic without duplicating too much code. Any suggestions on how to achieve this? I've managed to separate the state from the layout using render props. interface State { open: boolean; } interface InjectedMod ...