我正在验证用户的电子邮件地址。但是当我在没有验证电子邮件地址的情况下调用该函数和表单时出现了问题。请告诉我该代码有什么问题。
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';
}
return error; }
答案 0 :(得分:0)
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; }
试试吧!
答案 1 :(得分:0)
始终返回true或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;
}
}
按照以下方式调用您的函数: -
<input type="submit" onsubmit="return validateEmail(email.val)">