2013-07-10 48 views
0

我有一個問題,當我嘗試驗證字段,輸入名稱(例如),但正確輸入輸入密碼少於8個字符我刪除了「名稱」字段,同樣的事情發生當我輸入密碼並嘗試將空字段「名稱」。我顯示警報,但我清除了已經驗證的字段。這將是?問題與js驗證

<!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接受我的代碼

+0

爲什麼不能*接受*你的代碼? – gustavodidomenico

回答

1

您需要添加returnonclick屬性,以便於單擊處理程序會返回一個驗證函數返回。

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

否則,如果驗證失敗並且表單已提交,則不返回false

+0

+1,我會使用'onsubmit'事件而不是按鈕點擊事件。 – ocanal

+0

感謝您的幫助 – user1851950