...

View Full Version : "undefined" and I don't know why (validation and arrays)



]|V|[agnus
07-08-2004, 05:15 PM
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?

]|V|[agnus
07-08-2004, 09:22 PM
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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum