Skip to content

Instantly share code, notes, and snippets.

@SimonJThompson
Last active December 17, 2015 21:49
Show Gist options
  • Save SimonJThompson/5677724 to your computer and use it in GitHub Desktop.
Save SimonJThompson/5677724 to your computer and use it in GitHub Desktop.
/* This code will validate all elements in a form (elements that are included in form.elements, that is).
By "Validate", it is meant that the field is not empty. No additional checks are made such as for valid email addresses,
phone numbers or anything similar. Any empty / failed fields will be given a red border color and text before an alert appears informing the user that they need to complete the stated fields */
function validateForm(form)
{
var error_count = 0; // Holds the amount of errors
var error_list = new Array(); // The array (list) of errors found.
for( var i = 0; i< form.elements.length; i++) // Loop through the form elements
{
if(form.elements[i].value=="")
{
form.elements[i].style.color = "red"; // Set the text color
form.elements[i].style.borderColor = "red"; // Set the border color
error_list.push(form.elements[i].name); // Push the field name to the array of failed items / errors
error_count++; // Increment the error count
}else{
form.elements[i].style.color = "#222"; // Reset the text color
form.elements[i].style.borderColor = "#bababa"; // Reset the border color
}
}
if(error_count>0){alert("Please complete these fields:" + error_list); return false;}else{return true;} // Return a value and alert the errors.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment