Possible Duplicate:
Validate email address in Javascript?
我正在尝试使用此 JavaScript 来检查有效的电子邮件,但我不需要它做的是检查表单中的字段是否为空,以防有人没有电子邮件地址(别问)。
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;}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"Not a valid e-mail address.")==false)
{email.focus();return false;}
}
}
我尝试将 apos<1 调整为小于 1 或根本不调整,但这似乎不起作用。
最佳答案
只需检查它是否为空,否则应用您的 email regex/验证功能。
此外,您应该 a) 不使用 with
并且 b) 不要从测试函数中发出警报。
function test_email(address) {
var atpos = address.indexOf("@"),
dotpos = address.lastIndexOf(".");
if (atpos < 1) // "@" at position 0 or not found (-1)
return false;
if (dotpos-atpos < 2) // last "." before position 2 or not found (-1)
return false;
if (atpos > dotpos) // last "." before the "@"
return false;
return true;
}
function validate_form(thisform) {
var input = thisform.email;
if (input.value) // != ""
if (!test_email(input.value)) {
alert("Not a valid e-mail address.");
email.focus();
return false;
}
}
关于javascript - 检查表单中的电子邮件是否正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11633752/