Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate multiple form fields in one function

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

like image 439
Baraa Avatar asked Dec 02 '25 01:12

Baraa


1 Answers

Pass the id as an argument for the function and access the respected parameter. So instead of writing the entire code again and 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 parameter as the id you need to validate. eg return FormValidation("firstName")

like image 147
Harigovind R Avatar answered Dec 04 '25 13:12

Harigovind R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!