简体   繁体   中英

Validating e-mail address

I am trying to validate an e-mail address using javascript. The problem is the if statements aren't executing correctly. If I delete the 'else statement' the code runs correnctly and the page does not load with errors. If I include the 'else statement' the else statement never executes and the status bar says that the page loads with errors. I was wondering if anyone can find any errors that I am unable to pick up?

<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>
<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>

Read more: http://www.marketingtechblog.com/javascript-regex-emailaddress/#ixzz1wqetPJQQ

try this

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);
} 

Demo : Here is the demo

OR a more simpler way is

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

if you are using HTML5 try <input type="email"... please note. this one works if the input is in a form tag with a submit button and isn't handled by JS

<input type="email" placeholder="me@example.com">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM