Password check

Asked

Viewed 5,706 times

5

Hello, I’m starting to learn Javascript and I’m not being able to validate my code if there are 3 characters in uppercase, 2 numbers and 1 special character in my input. I would like to know what I must be doing wrong, because I have made several attempts, researched several sites and no way works. Follows 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!

2 answers

5


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
  • The code worked more unfortunately the only information it presents is that of "Else if".

  • Excellent @Felipe, much more practical

  • 1

    Imagine @Maiconcarraro! Yours checks for more special characters.

  • 1

    @Larissamourullo, I don’t understand, how so the only information is from else if?

0

It may not be the best way, but it is very educational. If you want to know about the values ASCII that I used in the code take a look here: http://www.asciitable.com/

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
  
  for (var i=0; i <= senha.length; i++) {
    var valorAscii = senha.charCodeAt(i);
    
    // de A até Z
    if (valorAscii >= 65 && valorAscii <= 90)
      letraMaiscula++;
    
    // de 0 até 9
    if (valorAscii >= 48 && valorAscii <= 57)
      numero++;
    
    // indexOf retorna -1 quando NÃO encontra
    if (caracteresEspeciais.indexOf(senha[i]) != -1)
      caracterEspecial++;
  }
        
  return (letraMaiscula >= 3) && (numero >= 2) && (caracterEspecial >= 1);
}
<form name="formulario">
  <input name="senha" />
  
  <input type="submit" onclick="return valido()"/>
</form>

  • The code didn’t even work unfortunately.

  • @Larissamourullo And what happened?

Browser other questions tagged

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