Good article! My thinking cap is tickle by articles like this one. It may not be perfect, but it encourages other to continue finding better solutions.
We combined some of the solutions and came up with this validation for Text and Empty fields while typing in the fields and at form submition:
<STYLE TYPE="text/css">
.badValue {background:red; color:white}
.goodValue {background:white; color:black}
</STYLE>
<SCRIPT LANGUAGE="JavaScript">
function validateEmpty() {
// Get the source element.
var el = event.srcElement;
// Valid not empty
var num = " ";
event.returnValue = false;
/* Loop over contents. If the field is empty,
set the return value to false. */
for (var intLoop = 0;
intLoop < el.value.length; intLoop++)
if (-1 == num.indexOf(el.value.charAt(intLoop)))
event.returnValue=true;
if (!event.returnValue) // Bad value
el.className = "badValue"; // Change class to badValue.
else
// Change class to goodValue.
el.className="goodValue";
}
function isEmpty(str) {
// Check whether string is empty.
for (var intLoop = 0; intLoop < str.length; intLoop++)
if (" " != str.charAt(intLoop))
return false;
return true;
}
function checkRequired(f) {
var strError = "";
for (var intLoop = 0; intLoop<f.elements.length; intLoop++)
if (null!=f.elements[intLoop].getAttribute("required"))
if (isEmpty(f.elements[intLoop].value))
strError += " " + f.elements[intLoop].name + "\n";
if ("" != strError) {
alert("Required data is missing:\n" + strError);
return false;
}
}
</SCRIPT>
<form method="post" ACTION="action " ONSUBMIT="return checkRequired(this);">
<input type="text" name="realname" size="50" maxlength="50" ONCHANGE="validateEmpty();" required>
<font color="RED" face="Arial" align="bottom">[Required]</font>
and so forth…