使用JavaScript进行电子邮件验证

时间:2012-12-06 17:05:06

标签: javascript

  

可能重复:
  Validate email address in Javascript?

这是我的第一篇文章,我有一个小问题。我正在尝试验证表单上的电子邮件地址,但没有运气。我在互联网上找到了这个片段,但它似乎没有用。我现在正在使用Javascript来验证它。我通常不使用JS,所以任何帮助都会受到赞赏。

<script type="text/javascript">
    function ValidateEmail(inputText)  
    {  
       var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;  
       if(inputText.value.match(mailformat))  
       {  
           document.forms.emailform();  
           return true;  
       }  
       else  
       {  
           alert("You have entered an invalid email address!");  
           document.forms.emailform();  
           return false;  
       }  
    }  

<?php
    $addemail .= '

        <form method="post" action="cart2.php" name="emailform" onsubmit="return validateEmail">
        ';
    $addemail .= '
            E-mail Address: <input type="text" name="email" value="'.$row6['email'].'" size="19" /><input type="hidden" name="cartid" value="'.$cart.'" />';
        if ( $emailerror != '' )
            {
                $addemail .= '<img src="images/email_error.png" width="16" height="16" hspace="4" alt="E-mail Error" />';
            }
        $addemail .= '
            <input type="image" name="Add E-mail Address" alt="Add E-mail Address" src="images/addemail.gif" style="vertical-align:middle" />
        </form>
    ';
    if ( $row6['email'] == '' )
        {
            $emailpresent = 0;
        }
    else
        {
            $emailpresent = 1;
        }
}
        $addemail .= '
                </td>
            </tr>
        ';
}

?>

2 个答案:

答案 0 :(得分:5)

看看这个如何在Javascript中完成的例子:

<html>

<head>
<script type="text/javascript">
<!--
function validateEmail() {
    var emailText = document.getElementById('email').value;
    var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*@[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
    if (pattern.test(emailText)) {
        return true;
    } else {
        alert('Bad email address: ' + emailText);
        return false;
    }
}

window.onload = function() {
    document.getElementById('email_form').onsubmit = validateEmail;
}
</script>

</head>
<body>

<form id="email_form">
<input type="text" id="email">
<input type="submit">
</form>

</body>
</html>


修改

如果您确定网页的用户使用 HTML5 兼容的浏览器,您可以出于同样的目的使用以下更简洁的示例:

<!DOCTYPE html>

<html>
    <body>
        <form>
            <input type="email" pattern="^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*@[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$">
            <input type="submit">
        </form>
    </body>
</html>

答案 1 :(得分:0)

onsubmit="return validateEmail()"

您必须在validateEmail之后添加括号才能调用它,否则它会假设您正在尝试返回方法。