验证电子邮件地址

时间:2012-06-04 17:47:35

标签: javascript

我正在尝试使用javascript验证电子邮件地址。问题是if语句没有正确执行。如果我删除'else语句'代码运行正常,页面不会加载错误。如果我包含'else语句',则else语句永远不会执行,状态栏会显示页面加载时出错。我想知道是否有人能找到任何我无法接收的错误?

<h4>Example 4:</h4>
<div style="border:3px dashed #aaa; width:200px;">
    <div id="text">e-mail: <input id="email" onblur="verifyEmail()"/></div>
    <div id="verification" > </div>
</div>

<script type="text/javascript">
function verifyEmail(){
    var email = document.getElementById("email").value;
    var atPos=0;
     var dotPos=0;

    atPos = email.indexOf("@");
    dotPos = email.lastIndexOf(".");

    if(atPos<=3 || dotPos<atPos+2 || dotPos+2>=email.length){
        document.getElementById("verification").innerHTML = "Invalid E-mail Address";
    }else{
        document.getElementById("verification").innerHTML = "Valid";
    }

}



</script>

2 个答案:

答案 0 :(得分:2)

<script language="javascript">
function checkEmail() {
var email = document.getElementById('emailaddress');
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>

了解详情:http://www.marketingtechblog.com/javascript-regex-emailaddress/#ixzz1wqetPJQQ

答案 1 :(得分:1)

试试这个

function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\
".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 

演示Here is the demo

或者更简单的方法是

function validateEmail(email) 
{
    var re = /\S+@\S+\.\S+/;
    return re.test(email);
}

如果您使用HTML5,请尝试<input type="email"...。如果输入在带有提交按钮的表单标记中并且不由JS处理

,则此方法有效
<input type="email" placeholder="me@example.com">