Error in counting uppercase characters

Asked

Viewed 62 times

2

I’m creating a role in jquery where the user enters his password, this function identifies how many uppercase characters are in this password, to calculate the strength of that password. I even managed to make this function count the uppercase characters, but still I could not get the desired result. For example: the function can count the uppercase characters when they are at the beginning of the password, but if the user type a lowercase character, the next uppercase characters will not be counted, and that is where the problem arises. Here is the link of the tests I performed: Here!.

2 answers

3

I’d do it this way: When changing the value of the "password" field, you would traverse the string of the same char by char to see if it is present in the range [65-90], which corresponds to the values [A-Z] in ASCII code.

$("#senha").change(function(){
    var senha = $("#senha").val();
    var qtdMaiuscula = 0;
    for(var i = 0; i < senha.length; i++)
        if(senha.charCodeAt(i) >= 65 && senha.charCodeAt(i) <= 90)
            qtdMaiuscula++;
    $('#teste').html( qtdMaiuscula );
});

A little clearer code, which has the same effect:

$("#senha").change(function(){
    var senha = $("#senha").val();
    var qtdMaiuscula = 0;
    for(var i = 0; i < senha.length; i++)
        if(senha[i] >= 'A' && senha[i] <= 'Z')
            qtdMaiuscula++;
    $('#teste').html( qtdMaiuscula );
});
  • Hello @Luis, because then, I’m doing this way because in my original layout I will implement a degrade bar with red colors for incorrect passwords, yellow for reasonable passwords and green for correct passwords, all this dynamically as the user type, understood?

2


Another alternative using regex.

$("#senha").change(function(){
    var senha = $("#senha").val();

    $('#teste').html(senha.replace(/[^A-Z]+/g, '').length);
});

DEMO

The expression [^A-Z]+ will only match characters in the range of A-Z.

  • It’s not right @Qmechanic! because all I care about is uppercase letters and the function returns a higher value. Try typing in this form the password: Aeaeefg.

  • @Brunoduarte See now.

  • Correct @Qmechanic, it worked perfectly. Vlw, hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.