PDA

View Full Version : Resolved Validating Email Address



Aeche
04-22-2009, 12:48 AM
I'm in the middle of a JavaScript class, and I've run into a problem with one assignment. ^^; I've been given a pre-written script and HTML code to work with, and am required to modify it. Here's one thing I have to do, via my instructor:


Add an "email" field to this form. This field should also validate as a valid email address. (Hint: after adding the form field to the form itself, your next step will be to expand the function named submitIt() by adding a second if statement to confirm the contents of the email field. You will want to paste into the header and use the validEmail() function which you will find in Script 7.15, highlighted in red on pages 192-3 of your textbook.)

Okay, so I know how to write the code to validate an email address, but I can't figure out how to call the validEmail() function in the submitIt() function. Here's what I have at the moment:


window.onload = loadDoc;

function loadDoc() {
resetForm(document.forms[0]);
}

function validEmail(emailAddr) {
var invalidChars = " /:,;";

if (emailAddr == "") {
return false;
}
for (var k=0; k<invalidChars.length; k++) {
var badChar = invalidChars.charAt(k);
if (emailAddr.indexOf(badChar) > -1) {
return false;
}
}
var atPos = emailAddr.indexOf("@",1);
if (atPos == -1) {
return false;
}
if (emailAddr.indexOf("@",atPos+1) != -1) {
return false;
}
var periodPos = emailAddr.indexOf(".",atPos);
if (periodPos == -1) {
return false;
}
if (periodPos+3 > emailAddr.length) {
return false;
}
return true;
}


function submitIt(inputForm) {

document.getElementById("formerrors").innerHTML=" "

if (validEmail(emailAddr)==false) {
document.getElementById("formerrors").innerHTML = "You must enter a valid
email address";
inputForm.emailAddr.focus();
inputForm.emailAddr.select();
return false;
}


if (inputForm.username.value == "") {
document.getElementById("formerrors").innerHTML = "You must enter your
name";
inputForm.username.focus();
inputForm.username.select();
return false;
}
}


I've been playing with it for hours, and it's probably just a small thing I've forgotten and can't find. ^^;; Any help would be greatly appreciated!

Aeche
04-22-2009, 05:50 PM
Nevermind, I posted the question on another board and got the answer. Here it is, in case anyone else experiences a similar problem:


document.getElementById("formerrors").innerHTML = "You must enter a valid
email address";

document.getElementById("formerrors").innerHTML = "You must enter your
name";

You must eliminate the line breaks.

Change as shown:-


function submitIt(inputForm) {
document.getElementById("formerrors").innerHTML=" ";
em = document.getElementById("emailAddr").value;
if (validEmail(em)==false) {