2
I need help validating a form using pure Javascript only.
I cannot make a message error if, for example, the user enters numbers in the username field. The same should happen if the user for example puts an invalid email, type "Aaaaaaaaaa".
I tried to do this in the username, as shown in the code below. If it leaves the field blank or exceeds 16 characters the error works normally. If it fills the message, it disappears, but if it puts numbers and other things the message that was to appear does not appear.
Javascript:
function validar(){
var usuario = document.getElementById("usuario").value;
var email = document.getElementById("email").value;
var senha = document.getElementById("senha").value;
var confirmarsenha = document.getElementById("confirmar-senha").value;
var usuario_correto = /^[A-Za-z]+$/;
var valido = true;
if(usuario.length < 2 || usuario.length > 16) {
document.getElementById("msg-usuario").innerHTML="* O nome de usúario precisa ter entre 2 a 16 caracteres";
valido = false;
}else if (usuario.match(usuario_correto)) {
document.getElementById("msg-usuario").innerHTML="* O nome de usúario só pode ter letras [A-Z/a-z]";
valido = false;
}else{
document.getElementById("msg-usuario").innerHTML="";
}
if(email=="") {
document.getElementById("msg-email").innerHTML="* O email é obrigatório";
valido = false;
}else{
document.getElementById("msg-email").innerHTML="";
}
if(senha.length < 5 || senha.length > 16) {
document.getElementById("msg-senha").innerHTML="* A senha precisa conter de 5 a 16 caracteres";
valido = false;
}else{
document.getElementById("msg-senha").innerHTML="";
}
if(confirmarsenha=="") {
document.getElementById("msg-confirmar-senha").innerHTML="* Confirme a senha";
valido = false;
}else{
document.getElementById("msg-confirmar-senha").innerHTML="";
}
return valido;
}
Form:
<form class="form-registrar" onsubmit="return validar()">
<input type="text" placeholder="Nome de usúario" class="form-campo" id="usuario">
<div class="form-msg-erro" id="msg-usuario"></div>
<br>
<input type="text" placeholder="Email" class="form-campo" id="email">
<div class="form-msg-erro" id="msg-email"></div>
<br>
<input type="text" placeholder="Senha" class="form-campo" id="senha">
<div class="form-msg-erro" id="msg-senha"></div>
<br>
<input type="text" placeholder="Confirmar senha" class="form-campo" id="confirmar-senha">
<div class="form-msg-erro" id="msg-confirmar-senha"></div>
<br>
<input type="submit" value="Registrar" class="form-campo-registrar">
</form>
If you do this type of validation on several pages of your application, it is worth studying the use of validation libraries, such as Yup, in order to avoid repeating code.
– Luiz Felipe
For the user name, it could be just
if (! usuario.match(/^[A-Za-z]{2,16}$/)) { usuario inválido }
(already checks if it has between 2 and 16 letters, and enters if it is not valid)– hkotsubo