我正在尝试使用 Javascript 进行简单的表单验证。在这种情况下,我有一个电子邮件文本输入,如果电子邮件不是有效的电子邮件或电子邮件地址已被占用,我希望它出错。有效的电子邮件部分错误正常,但电子邮件地址已被参与总是通过。
这是我的脚本代码
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function valemail()
{
var email = $('input#email').val();
var atpos=email.indexOf("@");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
document.getElementById("email").style.border="3px solid red";
document.getElementById('email_error').style.display = 'block';
document.getElementById('email_error').innerHTML = 'A valid email address is required';
} else {
if ($.trim(email) != '')
{
$.post('../ajax/registeremail.php', {email: email}, function(data)
{
if ($.trim(data) == 'That email address is already in use. If you have created an account,
<a href="../login.php">Login</a>')
{
document.getElementById("email").style.border="3px solid red";
document.getElementById('email_error').style.display = 'block';
$('div#email_error').text(data);
} else {
document.getElementById("email").style.border="3px solid #33FF33";
document.getElementById('email_error').style.display = 'none';
}
});
}
}}
</script>
我的 registeremail.php 文件独立工作,并且是:
<?php
include('../init.php');
//email validation
if (isset($_POST['email']) === true && empty($_POST['email']) === false) {
$email = $_POST['email'];
if (email_exists($email) === true) {
echo('That email address is already in use. If you have created an account, <a>Login</a>');
} else {
echo('Good');
}
?>
实际的文本输入和 div 代码是
<input class="input" type="text" tabindex="2" placeholder="Email*" style="height:20px;" name="email"
id="email" onchange="valemail()">
<div id="email_error"></div>
有谁知道为什么会这样?我真的很困惑。