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:
- If the field is empty,
.length
will return 0
. Obvious!
Look at your condition: ... $('#senha').val() == "" || $('#senha').val().length < 4 ...
.
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.
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):
But since not everything is perfect, some browsers and Internet Explorer (ah vá) are not compatible. You can check the compatibility here.