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

Headers with a 3 pixel stroke applied

I have a design on my website that includes a 3px stroke around the header text to maintain consistency. I don't want to use images for this due to issues with maintenance and site overhead. While I know about the text-stroke property, browser suppor ...

Dynamic value updates using jQuery input type formulas

I need help with a form that has two inputs: The first input allows the user to enter an amount, such as 1000. The second input is read-only and should display the value of the first input plus 1%. For example, if the user types in 1000 in the first fie ...

Why should <template> be used in Vuetify?

Exploring the possibilities of Vuetify 2.0 in my current project has led me to dive into the v-stepper component, designed for displaying progress through numbered steps. In the example provided in the playground, I noticed the use of the <template> ...

Maintaining Aspect Ratio and Adding Letterboxes with Next.js Image

In my Next.js app, there is a section dedicated to displaying selected photos from a gallery. It's crucial for this area to maintain a fixed size of 566px*425px as users navigate through images or when a photo is loading. While the layout is responsiv ...

Adjust various text lengths to fit web browser content

I am using a web browser within my Windows Form. I am populating it with text each time, with almost the same text size in each loop. The size of my web browser is fixed, and I want to automatically adjust the text content to fit the browser. For example, ...

Utilize CSS in the same way as the legend tag styling

I'm looking to create a stylish border around my HTML component. While I know the HTML legend element can achieve this, I want to use it outside of a form. For reference on using HTML Legend: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

Node.js readline: SyntaxError: Unexpected token =>

Currently, I am diving into node.js and have found myself in need of utilizing the readline module for a new project. Below is the code snippet that I extracted directly from the official readline module example. const readline = require('readline&ap ...

JavaScript Audio working on local machine but not on server due to HTML5 compatibility issues

For my project, I am utilizing audio and Javascript in the following way: To start, I populate an array with audio files: var soundArray = new Array(); for (i=0; i<6; i++) { soundArray[i] = new Audio('sounds/sound_' + i + audioExt); ...

Submitting a form using Ajax that was generated with the help of jQuery

Using a table with various rows, each row has an edit button. Upon clicking the edit button, a form is generated using ajax/json to populate the form data based on the selected row. An issue arises when setting up the ajax for this form. Although the met ...

Conceal/Vanish a Row within a Table - Utilizing jQuery

How can I use jQuery to hide a table row with a simple effect? I am looking for a fadeout effect or to hide the row slowly. Currently, my code hides it very quickly, similar to using document.getElementById('id').style.display='none&apos ...

Verify if the header value corresponds

How can I validate the header value in a Node.js application? I want to restrict access to a certain route only if the user includes a specific header and its value matches what is expected. For instance, let's say the route requires a header like Acc ...

The publish-subscribe feature appears to be ineffective

Recently starting with meteor, I learned about the importance of removing autopublish. So, I decided to publish and subscribe to a collection in order to retrieve two different sets of values. Here is the code on my meteor side: Meteor.publish('chann ...

Creating PDF files with PDFkit in Node.js while rendering HTML data

I am looking for a way to generate a PDF file using the 'PDFkit' library. The data is being retrieved from a MySQL database, and some of the content includes HTML tags. However, when I try to render the HTML data to PDF using the 'html-to-te ...

Ways to enhance widget titles with borders on Blogger

As a Blogger user, I am looking for guidance on how to add a border around the title of each widget/gadget. When I place widgets such as About Me, Follow Us, etc., in my sidebar, I want them to have borders like in this image. While I know how to customize ...

Strange Reselect selector actions

It seems like my selector function is only triggered when one of the arguments changes, not both. Here's the selector I'm using to retrieve transactions from the state and apply two filters to them: export const getFilteredTransactionsSelector ...

Executing a Python script asynchronously from a Node.js environment

I am currently managing a node.js program that handles approximately 50 different python script instances. My goal is to implement a throttling mechanism where only 4 processes can run in parallel at any given time. Initially, I attempted to create a simp ...

Exploring the JSON data received from PHP script via jQuery AJAX

In my program, I have created a web page with 5 radio buttons for selection. The goal is to change the picture displayed below the buttons each time a different button is chosen. However, I am encountering an issue during the JSON decoding phase after rec ...

Using the jQuery/JavaScript operator is similar to the SQL LIKE query with the wildcard %

Is there a way to search for a specific part of my input using JavaScript/jQuery? I've tried two different methods, but neither yielded any results. <script type="text/javascript> $("#button").click(function () { $("#DivToToggle").toggle(); ...

Utilizing Regular Expressions for extracting data from an HTML webpage

Is it possible to extract the response "Here is the solution" from an HTML document using Regular Expression? <b>Previous Query:</b> <b>Here is the answer</b> ...