// Form Validation by Strecher. Feel free to use this as long as you leave this header.

function validateForm(formID) { // form id need to be same as form name for setting attributes
theForm = document.getElementById(formID); // finds the form we need by id
theStr = 'You have to fill in these fields: \n'; // 1st line of error message
efields = '' // make sure empty fields count is empty every time function starts
for (i=0; i < theForm.elements.length; i++) { // loops through all elements of the form
ele = theForm.elements[i]; // ele is the current element
if (ele.value=='' && ele.className=='required') { // checks if the field is empty and has 'required' class
theStr += "\n " + ele.getAttribute('title'); efields++; ele.focus(); // gets title attribute off each field for alert
fcolor = ele.style.backgroundColor; // getting current background color
ele.style.backgroundColor="pink"; // setting background pink
ele.setAttribute("onkeyup", "if (this.value!='') {document." + formID + "." + ele.name + ".style.backgroundColor='"+fcolor+ "';}"); // when user types something into the field, background changed back to previous color
}}
if (efields){ // if any there are any empty fields alert will popup
alert (theStr); return false; // shows the alert and cancels user action
}}
 
/*
Basic setup:
HEAD
<script language="javascript" type="text/javascript" src="formValidation.js"></script>

BODY
<form id="form1" name="form1">
<input name="title" title="First Name" type="text" class="required"/>
<input type="submit" value="Next" onclick="return validateForm('form1');" />
</form>
*/