...

View Full Version : Validate email address



tdavis
12-22-2010, 04:48 PM
I have this script to validate contact form fields. It works fine for checking that fields are not blank. I added the valid email code, which I copied from the w3schools web site. But, it does not work. I am confused about how to reference the email form field name. That is really the only thing I changed, that is, I added the frm.elements to the email variable.

Can anyone please help?
Thanks!



function validate_form(frm)
{


frm.elements.name.className = "input";
frm.elements.email.className = "input";
frm.elements.subject.className = "input";
frm.elements.comments.className = "input";

var errors=0;


//
// NAME cannot be blanks
//
if (isBlank(frm.elements.name.value)) {
frm.elements.name.className = "inputreq";
errors++;
}

//
// EMAIL ADDRESS cannot be blanks
//
if (isBlank(frm.elements.email.value)) {
frm.elements.email.className = "inputreq";
errors++;
}

//
// SUBJECT cannot be blanks
//
if (isBlank(frm.elements.subject.value)) {
frm.elements.subject.className = "inputreq";
errors++;
}

//
// COMMENTS cannot be blanks
//
if (isBlank(frm.elements.comments.value)) {
frm.elements.comments.className = "inputreq";
errors++;
}

//
// EMAIL ADDRESS appears invalid
//
if (validate_email(frm.elements.email.value,"Not a valid e-mail address!")==false) {
alert("TEST");
frm.elements.email.focus();
return false;
}

//
// Errors
//
if (errors>0) {
alert("Please enter all fields!");
return false;
}

//No errors
//frm.submit();
}

function isBlank(value)
{
regexp = /^\s*$/
return (value==null || regexp.test(value));
}

// Validate email address
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}

tdavis
12-22-2010, 05:00 PM
Well, I guess I should have searched the forum before posting. I found this posted by phillipm, and it seems to work. So I guess I will use that unless anyone has and suggestions....



function validate_email(field,alerttxt){
if (!(/^([a-z0-9])([\w\.\-\+])+([a-z0-9])\@((\w)([\w\-]?)+\.)+([a-z]{2,4})$/i.test(field.value))) {
alert (alerttxt);
return false;
}
return true;
}

Philip M
12-22-2010, 06:19 PM
Well, I guess I should have searched the forum before posting. I found this posted by phillipm, and it seems to work. So I guess I will use that unless anyone has and suggestions....



function validate_email(field,alerttxt){
if (!(/^([a-z0-9])([\w\.\-\+])+([a-z0-9])\@((\w)([\w\-]?)+\.)+([a-z]{2,4})$/i.test(field.value))) {
alert (alerttxt);
return false;
}
return true;
}


Yes, that is the way to go! :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum