How to check the number of characters in a password field with jquery?

Asked

Viewed 434 times

1

I need to validate the password field to be between 6 and 12 characters. For this, I am trying this way:

    $('#form').on('submit', function(event){
        event.preventDefault();
        if($('#senha').val() == "" || $('#senha').val().lenght < 4 || $('#senha').val().lenght > 12){
           $("#msg-error").html('<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Sua senha deve ter entre 6 e 12 caracteres!</div>');                      
        }else{
           .....
       }

The HTML field:

<div class="styled-input">
    <label style="font-weight: normal" for="senha">Senha:<span style="color: red">*</span></label>
    <input type="password" name="Senha" maxlength="12" id="senha">
</div>

Only it’s not validating. How can I fix this?

2 answers

1

The problem

Look at that part:

$('#senha').val().lenght

The correct name of the method is .length;

Now just rewrite your condition:

$('#form').on('submit', function(event) {
    event.preventDefault();

    senha = $('#senha');
    alvo_erro = $('#msg-error');

    if (senha.val().length < 4 || senha.val().length > 12) {
        alvo_erro.html('<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i> Sua senha deve ter entre 6 e 12 caracteres!</div>');
    } else {
        //.....
        console.log('Passou na validação!');
        alvo_erro.empty();
    }
});
<!DOCTYPE html>
<html>
    <head>
        <title></title>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <meta charset="utf-8">

    </head>
    <body>
        <div class="styled-input">
            <form id="form">
                <label style="font-weight: normal" for="senha">Senha:<span style="color: red">*</span></label>
                <input type="password" name="Senha" maxlength="12" id="senha">
                <input type="submit" name="Submit!">
            </form>
        </div>
        <div id="msg-error"></div>
    </body>
</html>


Remarks:

  1. If the field is empty, .length will return 0. Obvious!

Look at your condition: ... $('#senha').val() == "" || $('#senha').val().length < 4 ....

  1. In your code you instantiate the input every time he wants to pursue his worth: $('#senha').val(). It is good practice to create a variable that takes the instance (caching). This relatively increases the performance of your application.

  2. Since the validation is being made directly in the client, the HTML also has the attribute minlength.

Behold:

<input type="password" name="Senha" minlength="4" maxlength="12" required id="senha">

Remember you need the required to ensure that the input was filled out.

And the warning is on the browser (in this example use Chrome):

Aviso do navegador

But since not everything is perfect, some browsers and Internet Explorer (ah vá) are not compatible. You can check the compatibility here.

0

You can do this way, the code is commented for better understanding.

//Deixei a mensagem de erro em uma função separada para que possa ser reaproveitada em outros trechos, e caso seja alterada ela será em apenas um lugar
function msgErro(mensagem){
	$("#msg-error").html('<div class="alert alert-danger" role="alert"><i class="fas fa-exclamation-triangle"></i>' + mensagem + '</div>'); 
}

$('#form').on('submit', function(event){
	event.preventDefault();
	
	// Verifica se a senha foi digitada
	if($('#senha').val().length == 0){
		msgErro('Favor preencher o campo senha');
		return false;
	}
		
	// No seu codigo você digitou lenght e o certo é length
	// Aqui verifica se o tamanho digitado esta entre 4 e 12
	if($('#senha').val().length < 4 || $('#senha').val().length > 12){
		msgErro('Sua senha deve ter entre 6 e 12 caracteres!');
		return false;
	}else{
		msgErro('');
		console.log("Tudo ok com a senha");
	}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
  <div id="msg-error"></div>
	<div class="styled-input">
		<label style="font-weight: normal" for="senha">Senha:<span style="color: red">*</span></label>
		<input type="password" name="Senha" maxlength="12" id="senha">
	</div>
  <input type="submit" value="enviar" />
</form>

Browser other questions tagged

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