我正在尝试使用 JavaScript 验证用户在 Web 登录表单上的输入,但有些东西让我发疯了,我不知道出了什么问题。限制:参考。number 必须是数字,并且 postcode 只能包含数字和字母。所以我通过几个函数来检查这个和输入字段的长度。此外还有 HTML 表单和 JavaScript 文件。编辑:所有验证方法都会失败,即使我没有在字段中输入值,它也会将我重定向到成功的登录页面。
<html>
<form method"POST" id="loginform" action="thank-you.html">
<table>
<tr>
<td> Post Code : <input id="postcode" type="text" required="required" /></td>
<td> Ref. Number :<input id="passw" type="password" required="required" /></td>
<td> <input type="submit" class="submit"value="Submit" </td>
</tr>
</table>
</form>
</html
和 javascrit 代码:
function formValidation() {
document.getElementById("loginform").onsubmit = function () {
var uid = document.loginform.postcode;
var passid = document.loginform.passw;
if (postcode_validation(uid, 5, 7)) {
if (passid_validation(passid, 4, 6)) {
if (alphanumeric(uid)) {
if (allnumeric(passid)) {}
}
}
}
}
return false;
}
function userid_validation(uid, mx, my) {
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx) {
alert("Postcode should not be empty / length be between " + mx + " to " + my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid, mx, my) {
var passid_len = passid.value.length;
if (passid_len == 0 || passid_len >= my || passid_len < mx) {
alert("Password should not be empty / length be between " + mx + " to " + my);
passid.focus();
return false;
}
return true;
}
function alphanumeric(uid) {
var letters = /^[0-9a-zA-Z]+$/;
if (uid.value.match(letters)) {
return true;
} else {
alert('postcode must have alphanumeric characters only');
uid.focus();
return false;
}
}
function allnumeric(passid) {
var numbers = /^[0-9]+$/;
if (passid.value.match(numbers)) {
return true;
} else {
alert('REf number must have numeric characters only');
passid.focus();
return false;
}
}
window.onload = function () {
formValidation();
}