Check input password

Posted on

Question :

Hello, I’m starting to learn JavaScript, and I’m not getting any way to make my code validate if there are 3 uppercase, 2 numbers, and 1 special characters in my input. I would like to know what I should be making of error, because I made several attempts, I researched in several sites and no way works. Here is the base code:

            /* Validação do Campo Senha*/
        if (document.formulario.senha.value.length < 8) {
           alert("A senha deve conter no minímo 8 digitos!");
           document.formulario.senha.focus();
           return false;
       }

Thank you for your attention!

    

Answer :

Larissa , use REGEX:

var senha = document.formulario.senha;
var regex = /^(?=(?:.*?[A-Z]){3})(?=(?:.*?[0-9]){2})(?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})(?!.*s)[0-9a-zA-Z!@#$%;*(){}_+^&]*$/; 

if(senha.length < 8)
{
    alert("A senha deve conter no minímo 8 digitos!");
    document.formulario.senha.focus();
    return false;
}
else if(!regex.exec(senha))
{
    alert("A senha deve conter no mínimo 3 caracteres em maiúsculo, 2 números e 1 caractere especial!");
    document.formulario.senha.focus();
    return false;
}
return true;

Explaining regex:

// (?=(?:.*?[A-Z]){3}) - Mínimo 3 letras maiúsculas
// (?=(?:.*?[0-9]){2}) - Mínimo 2 números
// (?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})(?!.*s)[0-9a-zA-Z!@#;$%*(){}_+^&] - Mínimo 1 caractere especial

    

Maybe not the best way, but it’s well didactic. If you want to know about the ASCII values I used in the code, take a look here: link

function valido() {
var senha = document.formulario.senha.value;

var letraMaiscula = 0;
var numero = 0;
var caracterEspecial = 0;
var caracteresEspeciais = "/([~'!@#$%^&*+=-[]';,/{}|":<

>

?])""

// adicione o que quiser pra validar como caracter especial

Leave a Reply

Your email address will not be published. Required fields are marked *