I have implemented the following code for a form to handle validation and display errors below the fields when they occur:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.errorcss {
background-color: yellow;
color:red;
}
</style>
<script type="text/javascript">
error = " ";
function isBlank(s) {
var len = s.length;
var i;
for (i = 0; i < len; ++i) {
if (s.charAt(i) != " ") return false;
}
return true;
}
function validate(fieldName, fieldValue) {
if (isBlank(fieldValue)) {
error = fieldName + " cannot be left blank.";
alert(fieldName + " cannot be left blank.");
return false;
}
return true;
}
function validatePass(passwordValue, confirmPasswordValue) {
if (passwordValue !== confirmPasswordValue) {
alert("Password and Confirm Password do not match");
return false;
}
return true;
}
function validateForm() {
if (!validate("The last name field", document.contest.last.value))
return false;
if (!validate("The email field", document.contest.email.value))
return false;
if (!validate("The password field", document.contest.pass.value))
return false;
if (!validatePass(document.contest.pass.value, document.contest.repass.value))
return false;
if (!validate("The description field", document.contest.desc.value))
return false;
}
</script>
</head>
<body>
<form name="contest" onSubmit = "return validateForm()" method="GET">
<h2 align="center">Sign Up Form</h2>
<p>
*Last Name:<input type="text" name="last" size="16">
First Name:<input type="text" name="first" size="12">
Middle Initial:<input type="text" name="initial" size="2">
</p>
<div class="errorcss">
<script type="text/javascript">document.write(error);</script>
</div>
<p>
*E-mail Address:<input type="email" name="email">
*Password:<input type="password" size="10" name="pass">
*Confirm Password:<input type="password" size = "10" name="repass">
</p>
<p>
In 50 words or less, describe yourself:
</p>
<textarea name="desc" ROWS="5" COLS="40"></textarea>
<p>
Submit your form:<input type="SUBMIT" value="Submit my form">
</p>
</form>
</body>
</html>
My current issue is that I want the "no last name" error to be displayed in the div with errorcss class, but it is not displaying. Additionally, I am exploring ways to display all errors when they occur using JavaScript and CSS.