[英]problems with js validation
當我嘗試驗證字段時,輸入名稱(例如)時出現問題,但輸入的密碼少於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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.