Validating multiple form fields in one function
I have the following code that is designed to validate a for field when entering values ββinto 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 checks will also be required for other fields.
I tried a for loop but it doesn't work to validate all forms like the above code for 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 greatly appreciated!
Thanks Al
source to share
Pass id as an argument to the function and access the respected parameter. So instead of writing all the code over and over again, you can call the function with your specific argument.
function FormValidation(id){
var fn=document.getElementById(id).value;
if(fn == ""){
document.getElementById(id).style.borderColor = "red";
return false;
}else if (/^[0-9]+$/.test(document.getElementById(id).value)) {
document.getElementById(id).style.borderColor = "red";
return false;
}else if(fn.length <=2){
document.getElementById(id).style.borderColor = "red";
return false;
}else{
document.getElementById(id).style.borderColor = "#679f30";
}
}
Call the function with the parameter as the identifier to be checked. eg
return FormValidation("firstName")
source to share