Error in uppercase count

2

I am creating a function in jquery where the user typing their password, this function identifies how many uppercase characters there are in this password, in order to calculate the strength of that password. I even managed to make this function count the uppercase characters, but I still 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 types a lowercase character, the next uppercase characters will not be counted, and that is where the problem arises. Here is the test link that I ran: Here! .

    
asked by anonymous 02.02.2015 / 11:58

2 answers

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 .

    
02.02.2015 / 12:51
3

I would do it as follows: By changing the value of the "password" field, I would run the string of the same char to char checking whether it is present in the range [65-90], which corresponds to the [A-Z] values 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 slightly 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 );
});
    
02.02.2015 / 12:04