js验证的问题

problems with js validation

本文关键字:问题 验证 js      更新时间:2023-09-26

我在尝试验证字段时遇到问题,输入名称(例如),但输入正确,输入的密码少于8个字符。我删除了"名称"字段,当我输入密码并尝试清空字段"名称"时也会发生同样的情况。我显示了警报,但清除了已验证的字段。会吗?

<!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不能接受我的代码

您需要将return添加到onclick属性中,以便单击处理程序将返回验证函数返回的内容。

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

否则,当验证失败并且表单已提交时,不会返回false