请检查代码
function validate() {
var name = document.getElementById("name");
var pwd = document.getElementById("pwd");
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
function validate() {
var name = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
if (name === null || name === "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
有一种更简单的方法来做你想做的事情。你可以使用form
的原生属性:
<form>
Username: <input type="text" minlength="2" required>
<br> Password: <input type="password" minlength="6" required>
<br>
<button type="submit">Submit</button>
</form>
- HTML元素应该在javascript之前,如下所示:
<!DOCTYPE html>
<html>
<body>
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
<script>
function validate() {
var name = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
</body>
</html>
您还没有提供完整的代码,所以我们无法真正帮助您。据我所知,你没有发出成功验证的警报。
您需要获取值,因此需要将.value添加到getElement函数中。