Email Validation Problem
I am Validating email address of a User. But problem appeared when i call that function and form is submitted without validating email address. Please tell me whats wrong with that code.
function validateEmail(fld) {
var error="";
var tfld = trim(fld.value);
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
var illegalChars= /[\(\)\&l开发者_JAVA百科t;\>\,\;\:\\\"\[\]]/ ;
if (fld.value == "") {
fld.style.background = 'Pink';
error = "You didn't enter an email address.\n";
} else if (!emailFilter.test(tfld)) {
fld.style.background = 'Pink';
error = "Please enter a valid email address.\n";
} else if (fld.value.match(illegalChars)) {
fld.style.background = 'Pink';
error = "The email address contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error; }
Always return true or false:-
function validateEmail(fld) {
var error="";
var tfld = trim(fld.value);
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (fld.value == "") {
fld.style.background = 'Pink';
error = "You didn't enter an email address.\n";
} else if (!emailFilter.test(tfld)) {
fld.style.background = 'Pink';
error = "Please enter a valid email address.\n";
} else if (fld.value.match(illegalChars)) {
fld.style.background = 'Pink';
error = "The email address contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
if (error == '')
{
return true;
}
else
{
alert(error);
return false;
}
}
Call your function like this:-
<input type="submit" onsubmit="return validateEmail(email.val)">
function validateEmail(fld) {
var error="";
var tfld = trim(fld.value);
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (fld.value == "" || fld.value.length == 0) {
fld.style.background = 'Pink';
error = "You didn't enter an email address.\n";
} else if (!emailFilter.test(tfld)) {
fld.style.background = 'Pink';
error = "Please enter a valid email address.\n";
} else if (fld.value.match(illegalChars)) {
fld.style.background = 'Pink';
error = "The email address contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error; }
try that!
精彩评论