Stop the removal of the CSS content property

When a user enters and re-enters their password, I have a form that checks the strength of the password and displays text accordingly. However, I noticed that if a user makes a mistake and uses the backspace to re-enter the password, the text from data-text is no longer displayed because the content property from the CSS is removed, possibly due to the backspace action. I have been unable to find a solution to prevent this removal.

// Password field
self.addEventListener("keyup", () => {
  let val = self.value;
  testPasswordStrength(val);
});

// check password strength
const testPasswordStrength = (value) => {
  const strengthText = document.getElementsByClassName('js-password-strength')[0];
  const strongRegex = new RegExp(
      '^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[=/\()%ยง!@#$%^&*])(?=.{8,})'
    ),
    mediumRegex = new RegExp(
      '^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})'
    );

  if (value) {
    if (strongRegex.test(value)) {
      strengthText.setAttribute('data-validation-text', strengthText.dataset.textStrong);
      return "strong";
    } else if (mediumRegex.test(value)) {
      strengthText.setAttribute('data-validation-text', strengthText.dataset.textGood);
      return "medium";
    } else {
      strengthText.setAttribute('data-validation-text', strengthText.dataset.textDefault);
      return "weak";
    }
  } else {
    strengthText.classList.add("d-none");
  }
};
content: attr(data-validation-text);
<div class="js-password-strength" data-validation-text data-text-default="Password must be 8+ characters" data-text-good="Good password" data-text-strong="Great password">
</div>

Answer №1

Do you find this solution effective?

// Implementing password field functionality
const passwordField = document.getElementsByClassName('js-password-strength')[0];
passwordField.addEventListener("keyup", () => {
   let val = passwordField.textContent;
   checkPasswordStrength(val);
});

// Password strength evaluation function
const checkPasswordStrength = (value) => {
;
    const strongRegex = new RegExp(
        '^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[=/\()%ยง!@#$%^&*])(?=.{8,})'
        ),
        mediumRegex = new RegExp(
            '^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})'
        );

    if (value) {
        if (strongRegex.test(value)) {
            passwordField.setAttribute('data-validation-text', passwordField.dataset.textStrong);
            return "strong";
        } else if (mediumRegex.test(value)) {
            passwordField.setAttribute('data-validation-text', passwordField.dataset.textGood);
            return "medium";
        } else {
            passwordField.setAttribute('data-validation-text', passwordField.dataset.textDefault);
            return "weak";
        }
    } else {
        passwordField.classList.add("d-none");
    }
};
.js-password-strength{
  border:1px solid #000;
}
.js-password-strength:after{
content: attr(data-validation-text);
font-size:12px;
color:#666;
}
<html>
   <head>
   </head>
   <body>
      <div class="js-password-strength"
      data-validation-text
      data-text-default="Password must be 8+ characters"
      data-text-good="Good password"
      data-text-strong="Great password" contenteditable=true>
      </div>
   </body>
<html>

Answer №2

Hey @AndrewL64, I've pinpointed the issue to be with the line of code:

strengthText.classList.add("d-none");
This line is causing the content to not display by setting it to 'none'. To ensure the content is displayed when a value is set, we need to include display: block property.

 if (value) {
        strengthText.classList.remove("d-none");
        strengthText.classList.add("d-block");
        if (strongRegex.test(value)) {
            strengthText.setAttribute('data-validation-text', strengthText.dataset.textStrong);
            return "strong";
        } else if (mediumRegex.test(value)) {
            strengthText.setAttribute('data-validation-text', strengthText.dataset.textGood);
            return "medium";
        } else {
            strengthText.setAttribute('data-validation-text', strengthText.dataset.textDefault);
            return "weak";
        }
    } else {
        strengthText.classList.remove("d-block");
        strengthText.classList.add("d-none");
    }

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

Every time I attempt to visit my website on a mobile device, it seems to appear larger than normal, as

After developing a responsive website and adding media queries to make it mobile-friendly, I encountered an issue. Despite my efforts, the website's width is still larger than the mobile viewport, requiring users to zoom out to view it properly as sho ...

Align the UL in HTML to be on the same line as other spans

When examining this jsFiddle demonstration at the following link: http://jsfiddle.net/jrXwf/1/ The UL tag showcases a star rating, with accompanying text displayed on the line below it. Is there a method to have everything appear on a single line? Appre ...

Utilize jQuery to dynamically assign classes to list items within a unordered list based on the length of an array

HTML: <ul class="tickboxes"> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i>< ...

Error code "ER_BAD_FIELD_ERROR" was encountered with errno 1054 and sqlState "42S22" in index 0 while using MySQL with Angular and managing sessions

When I log in, the following code is executed: <div ng-include="'partials/navbar'"></div> <form name="form" ng-submit="login(form)"> <div> <input type="text" placeholder="Email" ...

What is the best way to format a condensed script into a single line?

There are times when the script in the web browser is packed into one line like function a(b){if(c==1){}else{}}. I have attempted to locate something that would display it in a more normal format. function a(b) { if(c==1) { } else { } } Howev ...

Discover if every single image contains a specific class

HTML : <div class="regform"><input id="username" type="text" name="username" placeholder="Username" required><h3 class="check"><img src=''/></h3></div> <div class="regform"><input id="password" type=" ...

Trouble with passing the function variable to setState efficiently

Although I haven't worked with React for a while, it seems like this issue is more related to plain JS. Here is the setState function that I am using: // click event on parent for performance reasons ``Component:`` const [active, setActive] = useSta ...

What alternative methods are available to rename a field that has been returned in mongoose, if at all possible?

I need help with this specific query: MessageModel.find({ conversationId: { $in: ids } }) .sort({createdAt: 'ascending'}) .populate({ path: 'receiver', select: '_id' }) .populate({ path: &a ...

Harnessing the power of two-way data binding in VueJS

I am looking to utilize Vue's two-way data binding to dynamically update the values of amount and total. The price of a given product is fixed. When users modify the amount, the total = amount * total will be automatically calculated. Similarly, users ...

Rendering a component and updating state with inline onClick event handlers

When discussing the concept of pure render methods in React and highlighting the serious anti-pattern of setting state inside the render function, how strictly should this be adhered to? It is understood that triggering a setState within the render functio ...

Empty space under the banner in Wordpress theme Avada

I can't seem to locate the CSS class for a blank space that appears below the header on one of my pages. This space is situated between the header and "SERVICIOS 24 HORAS". Any ideas on how I can remove this mysterious gap? My website is built wit ...

call a custom form submission using jquery first, followed by a regular form submission

Is it possible to attach a submit() handler to a form in order to execute an ajax request, and then have the form submit itself normally once the request is complete? Using $('#myForm').submit() seems to just result in the same function being cal ...

What is the method for adjusting the position of this box-shadow?

As a beginner in coding, I stumbled upon this box shadow effect online but I am struggling to adjust it to match the font style I am using. Here is the CSS for the title: .sidebar-title { position:absolute; z-index:150; top:100px; left:330px; ...

Accessing Headers in node request library

I need help retrieving the server response header for a request from a server. import 'request' from 'request' var url = "SOME_URL" var options = { url: url }; var callback = function(error, response, body) { if(!error){ ...

What steps should I take to resolve the 'buffer' issue in my jsonwebtoken?

As I am still new to ReactJS and the MERN stack in general, the code in Activate.js below essentially means that when the useEffect() hook is triggered, we will receive the jwt token extracted from the route parameter/url using the {match} props. This toke ...

Django redirects to an alternative template instead of the default one

After renaming my login.html file to login1.html instead of deleting it, I have been using Django-registration and Django-registration-views from Github. However, despite this change, Django continues to call registration/login1.html. Is there a way for me ...

Placement of navigation bar on top of picture

Creating a gaming website and encountering challenges with text alignment. The goal is to have the navbar text positioned on top of a customized navbar background. Current appearance navbar example <!DOCTYPE html> <html> <head> ...

How to retrieve the image source from a block using jQuery

Currently, I am working on developing a slider for my webpage using jquery's "Cycle" plugin. However, I have encountered an issue with accessing the image sources used in the slider. To provide more context, here is a snippet of code from the 'he ...

Node app experiencing issues with passport authentication request route only in production mode

Currently, I am facing an issue with my MERN app that includes passport for authentication flow. It runs smoothly in development mode but encounters major problems in production mode that I am struggling to resolve. The bug seems elusive and I can't p ...

jquery selector targeting a select optiongroup that contains a specific label value

In my code, I have a select multiple with option groups: <select _ngcontent-oeq-14="" class="form-control" id="category-select" multiple=""> <optgroup label="grocery products"> <option>meat</option> <option>dai ...