我目前正在尝试使用 JS 创建一个非常简单的验证脚本。基本上,如果输入到表单中的文本短于 5 个字符或长于 25 个字符,我希望出现警报。
<!doctype html>
<html>
<head>
<title>Password Validator</title>
</head>
<body>
<script>
function validate()
{
var yourpw = document.forms.passwordform.yourpassword.length;
if (yourpw < 5);
{
alert("password is too short");
return false;
}
if (yourpw > 25)
{
alert("your password is too long")
return false;
}
}
</script>
<h1>Password Validator</h1>
<p>Please create a new password below</p>
<p>Be sure you password follows these guidelines</p>
<ul>
<li>No shorter than 5 characters</li>
<li>No longer than 25 characters</li>
</ul>
<br>
<form name="passwordform" method="post" onsubmit="validate();">
<input type="text" name="yourpassword">
<br>
<input type="submit">
</form>
</body>
</html>
我不确定我到底遗漏了什么或为什么它不起作用,但我想要的目标是当文本输入名为“yourpassword”的文本框时,将运行一个脚本,如果有任何一个,它将显示一条消息满足以下条件之一:短于 5 个字符,或长于 25,警告输入密码的人不符合准则,如果密码符合准则,那么我只想显示一条简单的确认消息。无论如何,我感谢任何帮助,因为这让我很沮丧,让我想放弃学习 JS。谢谢
最佳答案
您需要首先阻止表单提交的默认行为。
使用
function validate(e)
{
e.preventDefault();
var yourpw = document.forms.passwordform.yourpassword.value.length;
... rest of code
}
关于简单表单验证所需的 Javascript 帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34259549/