Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    May 2004
    Location
    Minneapolis, MN, USA
    Posts
    904
    Thanks
    0
    Thanked 0 Times in 0 Posts

    "undefined" and I don't know why (validation and arrays)

    Code:
    function validateContact() {
    	var d = document;
    	var name = d.getElementById("name");
    	var email = d.getElementById("email");
    	var comments = d.getElementById("comments");
    	var errors = new Array();
    	
    	// Validate name
    	if (name.value == "") {
    		errors[errors.length] = "You must enter a name.";
    	}
    	
    	// Validate email
    	var validEmail = /^[[:alnum:]._%-]+@[[:alnum:]._%-]+\.[[:alnum:]._%-]{2,4}$/g;
    	if (email.value == "") {
    		errors[errors.length] = "You did not enter an email address.";
    	} else if (!email.value.match(validEmail)) {
    		errors[errors.length] = "You did not enter a valid email address.";
    	}
    	
    	// Validate comments
    	if (comments.value == "") {
    		errors[errors.length] = "You did not enter any comments.";
    	}
    	
    	// Prompt with errors if there were any
    	if (errors.length > 0) {
    		alert(errors.length);
    		var errorMsgs;
    		for (e=0; e<errors.length; e++) {
    			errorMsgs += errors[e] + "\n";
    		}
    		alert(errorMsgs);
    		return false;
    	}
    }
    This is a script I put together today to validate a simple contact form with three fields. All my conditions check properly, but then the errorMsgs are alerted, the first one always has "undefined" prepended to it. So like, "undefinedYou did not enter a name." would be the first line if the name field were left blank. Why is this happening?

  • #2
    Regular Coder
    Join Date
    May 2004
    Location
    Minneapolis, MN, USA
    Posts
    904
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Figured it out:

    var errorMsgs;

    I didn't know that declaring the variable without assigning an initial value, even an empty string, makes it's value "undefined", hence why the beginning of the final errorMsgs always had that at the beginning. I just changed that line to:

    var errorMsgs = "There are problems with your submission:\n\n";

    All error messages are appended after that still.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •