I have the following code that is for validating a for field as you are inputting values in the field (red for invalid and green if the field becomes valid):
function FormValidation(){
var fn=document.getElementById("firstName").value;
if(fn == ""){
document.getElementById("firstName").style.borderColor = "red";
return false;
}else if (/^[0-9]+$/.test(document.getElementById("firstName").value)) {
document.getElementById("firstName").style.borderColor = "red";
return false;
}else if(fn.length <=2){
document.getElementById("firstName").style.borderColor = "red";
return false;
}else{
document.getElementById("firstName").style.borderColor = "#679f30";
}
}
These validations will also be required for other fields.
I tried a for loop, but it doesn't work to validate all of the forms as the code above does for the one field:
function FormValidation(){
var array = ["firstName", "middleName", "lastName"];
for(i=0; i < array.length; i++){
var fn=document.getElementById(array[i]).value;
if(fn == ""){
document.getElementById(array[i]).style.borderColor = "red";
return false;
}else if (/^[0-9]+$/.test(document.getElementById(array[i]).value)) {
document.getElementById(array[i]).style.borderColor = "red";
return false;
}else if(fn.length <=2){
document.getElementById(array[i]).style.borderColor = "red";
return false;
}else{
document.getElementById(array[i]).style.borderColor = "#679f30";
}
}
}
So my question is am I doing something wrong? Or is there a way to validate more than one form in one function without having to write the same code over and over.
Any help is much appreciated!
Thank you, Al