Currently, I am studying the section of a book that covers form validation using JavaScript. Unfortunately, the example in the book is not functioning as expected. Despite comprehending and following the logic behind the validation process, nothing occurs onSubmit. I have meticulously reviewed both the script and HTML multiple times but have been unable to identify any errors (I even visited the book's website and copied the code from there).
Below is the HTML form along with the JavaScript validation:
<script>
function validate(form)
{
fail = validateForename(form.forename.value)
fail += validateSurname(form.surname.value)
fail += validateUsername(form.username.value)
fail += validatePassword(form.password.value)
fail += validateAge(form.age.value)
fail += validateEmail(form.email.value)
if (fail == "") return true
else {alert(fail); return false }
}
</script>
<script>
function validateForename(field) {
if (field == "") return "No Forename was entered.\n"
return ""
}
function validateSurname(field) {
if (field == "") return "No Surname was entered.\n"
return ""
}
function validateUsername(field) {
if (field == "") return "No Username was entered.\n"
else if (field.length < 5) return "Usernames must be at least 5 characters.\n"
else if (/[^a-zA-Z0-9_-]/.test(field)) return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\n"
return ""
}
function validatePassword(field) {
if (field == "") return "No Password was entered.\n"
else if (field.length < 6) return "Passwords must be at least 6 characters.\n"
else if (! /[a-z]/.test(field) || ! /[A-Z]/.test(field) || ! /[0-9]/.test(field)) return "Passwords require one each of a-z, A-Z and 0-9.\n"
return ""
}
function validateAge(field) {
if (isNAN(field)) return "No Age was entered.\n"
else if (field < 18 || field > 110) return "Age must be between 18 and 110.\n"
return ""
}
function validateEmail(field) {
if (field == "") return "No Email was entered.\n"
else if (!((field.indexOf(".") > 0) && (field.indexOf("@") > 0)) || /[^a-zA-Z0-9.@_-]/.test(field)) return "The Email address is invalid.\n"
return ""
}
</script>
</head>
<body>
<table class="signup" border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee">
<th colspan="2" align="center">Signup Form</th>
<form method="post" action="adduser.php" onSubmit="return validate(this)">
<tr><td>Forename</td><td><input type="text" maxlength="32" name="forename" /></td>
</tr><tr><td>Surname</td><td><input type="text" maxlength="32" name="surname" /></td>
</tr><tr><td>Username</td><td><input type="text" maxlength="16" name="username" /></td>
</tr><tr><td>Password</td><td><input type="text" maxlength="12" name="password" /></td>
</tr><tr><td>Age</td><td><input type="text" maxlength="3" name="age" /></td>
</tr><tr><td>Email</td><td><input type="text" maxlength="64" name="email" /></td>
</tr><tr><td colspan="2" align="center">
<input type="submit" value="Signup" /></td>
</tr></form></table>
</body>
</html>