Array showing wrong count

Hello
I’m working on a registration form and with it a div to display error messages.
looking just at the first two field (email and first name), if the field is empty it throws a error message. if one of the field is empty the array instead of just holding the one error message it has a empty value which throwing my script.

I tired couple of ways to iterate through the code but i cant seem to get past that empty value in the array.

this runs a function and updates the errUserInput array.

errUserInput.push(isValidEmail) + "<br/>";
errUserInput.push(isValidFirstName) + "<br/>";

this iterates through the errUserInput array and adds to the div tag to for dispaly.

if(errUserInput.length != 0) {
        for(let i=0; i < errUserInput.length; i++) {     
            if(typeof errUserInput[i] != null) {
                document.getElementById("errorStatus").innerHTML += errUserInput[i] + "<br/>";            
            }
        }    
        document.getElementById("errorStatus").style.display = "block"; 
        
    } else {
       document.getElementById("errorStatus").style.display = "none"; 
    }

Instead of copy/pasting email and first name validation scripts i copy/pasted the first name validation field to make a quick reference.

// validate user input first name
function validateFirstName(fName) {
    let isFirstName;
    const matchFirstName = /^.[a-zA-Z]{1,50}$/g;
    if(fName !== '') {       
        if(!fName.match(matchFirstName)) {     
           isFirstName = false;
        }     
     } else { 
        isFirstName = false;
     } 

     if(isFirstName == false) {    
        return "First name failed";       
     } 
} //END validate first name

Hi @robin01, the typeof operator returns a string with the primitive type of the respective value, but you’re checking against the actual values null / undefined. – So it should be either…

if (typeof errUserInput[i] !== 'undefined') {
  // ...
}

… or…

if (errUserInput[i] !== undefined) {
  // ...
}

… or actually you could probably just do:

if (errUserInput[i]) {
  // ...
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.