Implementing jQuery form validation including checking for the strength of the password

My understanding of jQuery was quite basic until I began working on jQuery form validation with password strength check. I successfully completed the password strength check portion, but now I am unsure of how to enable the submit button once the conditions are met.

Below is the code I have been working on:
https://codepen.io/jagan/pen/rzZqMq

Answer №1

implementing the disable and enable functionality for a button based on the status bar is a quick fix for any issues that may arise. However, to make it more robust and versatile, consider using a flag that remains false if the validation is not clean and only switches to true when the validation aligns with your requirements.

$(document).ready(function(){  
    $('#password').keyup(function(){
        var valid = true; 
        $('#result').html(checkStrength($('#password').val()));
                //Calculated strength value, we can return messages
        if( !valid){
            alert('errorMessage');
           }

    });  


    function checkStrength(password){
        var strength = 0;


        //If password contains both lower and uppercase characters, increase strength value.
        if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
             strength += 1 ;
             $('.low-upper-case').addClass('text-success');

        }
        else{
            $('.low-upper-case').removeClass('text-success');
             valid = false;
        }

        //If it has numbers and characters, increase strength value.
        if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)){
            strength += 1;
            $('.one-number').addClass('text-success'); 

        } 
        else{
            $('.one-number').removeClass('text-success');
             valid = false;
        } 

        //If it has one special character, increase strength value.
        if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) {
            strength += 1;
            $('.one-special-char').addClass('text-success');

        }
        else{
            $('.one-special-char').removeClass('text-success');
             valid = false;
        }

        if (password.length > 7){
         strength += 1;
         $('.eight-character').addClass('text-success');

        }
        else{
            $('.eight-character').removeClass('text-success');
            valid = false;
        }




       // If value is less than 2

        if (strength < 2 )
        {
            $('#result').removeClass()
            $('#password-strength').addClass('progress-bar-danger');
            $('#result').addClass('text-danger')
            $('#password-strength').css('width', '10%');
            $("#sign-up").attr("disabled",true)
            return 'Very Weak'           
        }
        else if (strength == 2 )
        {
            $('#result').removeClass()
            $('#result').addClass('good');
            $('#password-strength').removeClass('progress-bar-danger');
            $('#password-strength').addClass('progress-bar-warning');
            $('#result').addClass('text-warning')
            $('#password-strength').css('width', '60%');
           $("#sign-up").attr("disabled",true)
            return 'Week'       
        }
        else if (strength == 4)
        {
            $('#result').removeClass()
            $('#result').addClass('strong');
            $('#password-strength').removeClass('progress-bar-warning');
            $('#password-strength').addClass('progress-bar-success');
            $('#result').addClass('text-success');
            $('#password-strength').css('width', '100%');
            $("#sign-up").attr("disabled",false)
            return 'Strong'
        }

    }

        // if (passwordStatus == true){
        // $('#sign-up').prop("disabled", false);   
        // }
});

Answer №2

Review the following code snippet, where a global JavaScript variable is used to validate passwords with an initial value of false.

 function assessPasswordStrength(password){
      var isValid = true;
        var strengthLevel = 0;


        //Check if password contains both lowercase and uppercase characters to increase strength level.
        if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
             strengthLevel += 1 ;
             $('.low-upper-case').addClass('text-success');

        }
        else{
            $('.low-upper-case').removeClass('text-success');
             isValid = false;
        }

        //Check for presence of numbers and characters to boost strength level.
        if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)){
            strengthLevel += 1;
            $('.one-number').addClass('text-success'); 

        } 
        else{
            $('.one-number').removeClass('text-success');
             isValid = false;
        } 

        //Include one special character to enhance strength level.
        if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) {
            strengthLevel += 1;
            $('.one-special-char').addClass('text-success');

        }
        else{
            $('.one-special-char').removeClass('text-success');
             isValid = false;
        }

        if (password.length > 7){
         strengthLevel += 1;
         $('.eight-character').addClass('text-success');

        }
        else{
            $('.eight-character').removeClass('text-success');
            isValid = false;
        }
         if (isValid){
        $('#sign-up').prop("disabled", false);   
        }



    }

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 causing the left-to-right scrollbar in this Bootstrap template?

Currently delving into the realm of Bootstrap 4, I decided to experiment with creating a personal study template using this technology. However, after implementing the code, I noticed an unexpected left-to-right scrollbar appearing when viewing the website ...

"Create a flexible CSS grid with a dynamically changing number of rows and customizble

I am currently working on a project that involves creating a dynamic grid layout with two resizable columns, namely #red-container and #green-container. The goal is to make each column resizable horizontally while also allowing the main container #containe ...

The Main page is being graced by a floating Twitter Bootstrap video

When trying to display a video next to a paragraph, I encountered an issue where the paragraph was taking up 100% of the screen and the video was floating over it, obstructing part of the text. Despite setting the row and cols, the layout wasn't behav ...

What are the different applications of npm packages?

Is it possible to use npm packages in any Javascript runtime environment? I have experience using them in Angular and Node, but are they universally compatible across all environments? Edit: To those who downvoted this post, as a newcomer seeking assistan ...

Is it possible to postpone sending a message on Discord until a certain event has been successfully completed?

After the User leaves the Discord, I attempted to create a RichEmbed Message that would include a random GIF from Giphy. The GIF was meant to be generated using the getGiphyPic() function with the help of this node module: https://github.com/risan/giphy-ra ...

Encountering a ReactJS Prop Type Error due to an 'undefined' Value

Despite searching for answers in similar questions, I've been unable to find a solution... An error message is appearing: Warning: Failed prop type: The prop height is marked as required in AudioPlayer, but its value is undefined. This error occu ...

Adding variables to a div using jquery

Is there a way to use jQuery to append variables to a div? Below are my codes, but I am looking to display div tags in the append. For example: .append("" + p + "") var image = item.image; var label = item.label; var price = item.price; ...

Implementing ESM in your next.config.js file is critical for optimizing

Currently, I am in the process of optimizing a Next.js project and came across the requirement to include type: 'module' in thepackage.json file. However, this led to an error being thrown: Error [ERR_REQUIRE_ESM]: Must use import to load ES Mo ...

Remembering position in JSP using Java Beans

In my "Web Engineering" assignment, I am tasked with developing a Web Application game using JSP, Servlets, and Java Beans. The game mechanics are already in place with the Servlet controlling the algorithms, JSP handling the Model/View, and Beans managing ...

Why do I keep encountering a null window object issue while using my iPhone?

Hey there! I've got a React game and whenever the user loses, a new window pops up. const lossWindow = window.open( "", "", "width=500, height=300, top=200, left = 200" ); lossWindow.document.write( & ...

Implement jQuery Tabs in Brackets software to enhance user experience

My Adobe Creative Cloud subscription is expiring soon, and I am considering switching to Brackets, an open-source code editor developed by Adobe. However, I am facing some difficulties adding jQuery tabs to my HTML documents. I downloaded the 1.10.4 zip f ...

Error: Module not located or Image unable to load in React JS

Here is the structure of my project : src -assets fut.png -components -admin_dashboard Sidebar.js -App.js -pages Dashboard.js I encountered an issue trying to load the image fut.png from the file Sidebar.js. Even after attempting ...

divs adjust their size based on how many are placed in a single row

I'm in the process of developing an online editing tool, and I'm interested to know if it's feasible to adjust the size of a <div> based on the number of visible div elements. For instance, I have a row with three columns, each set at ...

Is there a way to adjust the image opacity of a background using Material UI?

Is there a way to adjust the opacity of a background image using Material UI? I attempted to achieve this by utilizing the makeStyles hook in Material UI. Here is an example of my code: import React from 'react'; import {Box,Typography } from &ap ...

Add a stylish diagonal touch to your header and footer using CSS

I'm exploring the world of CSS and design, aiming to incorporate a stylish diagonal line into the header and footer of my React.js web application using CSS. However, despite trying various solutions, I haven't been successful in achieving the de ...

Methods for dynamically populating dropdown lists with JavaScript and Bootstrap

I have collected all 387 regions for the current date and now I want to dynamically populate a bootstrap dropdown with these regions using JavaScript. Below is the basic HTML code for a bootstrap dropdown: <div class="dropdown"> <button class ...

Custom CSS file for individual tenants in the Twig main template

Our Symfony 2.4 application is a multi-tenant system, meaning we share the same codebase among several organizations and differentiate access by domain name. For example: organization1.domain.com organization2.domain.com organization3.domain.com We util ...

Glowing semi-opaque about spotify?

Recently, I decided to challenge myself by recreating the Spotify homepage using only pure Javascript and SCSS as a way to test my front-end development skills. You can view my progress so far at this link, although please note that it's still a work ...

The web server is serving an HTML file instead of the expected JSON response

Is there a way to extract the JSON data from ? I have tried using AJAX but it only retrieves the entire HTML page instead. $.ajax({ url: 'http://www.bartdekimpe.be/anoire/index.php/admin/getGamesUserJson/34', success: function(data) { ...

What is the best way to alter the font size in an SVG?

I have incorporated an SVG icon into my website and obtained the following code from Adobe Illustrator: <svg id="Livello_1" data-name="Livello 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448.05 436.7"><path d="M190.5,66.9l22.2-22.2a23.9, ...