简体   繁体   中英

problems with js validation

I have a problem when I try to validate the fields, entering the name (for example), but entered correctly enter the password with less than 8 characters I deleted the "name" field, the same thing happens when I enter the password and try to put empty the field "Name". I shows the alerts, but I cleared the fields that have already been validated. it will be?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />     
        <title>Ejercicio 3 v4</title>
        <script type ="text/javascript" src="codigo4.js"> </script> 
  </head>
  <body>
    <form id="formulario" action="#" method="post">
        <label for="nombre">Usuario:</label>    
        <input name="nombre" id="nombre" type="text" />
        <br></br>   
        <label for="clave">Password:</label>    
        <input name="clave" id="clave" type="password" />
        <br></br>
        <label for="reclave">Reingrese Password:</label>    
        <input name="reclave" id="reclave" type="password" />
        <br></br>
        <input name="boton" id="boton" type="submit" onclick="validar()" value="Enviar" />
    </form> 
  </body>
</html>

codigo4.js

function validar(){
    var usuario = document.getElementById("nombre").value;
    var pass = document.getElementById("clave").value;
    var repass= document.getElementById("reclave").value;

    if (usuario =="")
    {
        alert("debe poner un nombre");
        return false;
    }
    else if(usuario.length < 2 )
    {
        alert("nombre debe tener mas de 2 caracteres");
        return false;
    }
    else if(pass =="")
    {
        alert("debe poner un password");
        return false;
    }   
    else if (pass.length < 8 )
    {
    alert("clave debe tener mas de 8 caracteres");
    return false;
    }
    else if (repass.length < 8 )
    {
    alert("clave debe tener mas de 8 caracteres");
    return false;
    }
    else if (pass != repass)
    {
    alert("las contrase��as no coinciden");
    return false;
    }

alert("todos los campos son validos");
return true;
}

pd: jsfiddle can´t accept my code

You need to add return to the onclick attribute, so that the click handler will return what the validation function returns.

<input name="boton" id="boton" type="submit" onclick="return validar();" value="Enviar" />

Otherwise, you don't return false when validation fails, and the form is submitted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM