我正在嘗試使用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>
做有誰知道爲什麼會發生這種情況?我真的很困惑。
打開控制檯,找出是否有任何錯誤。 – Prasanth
爲什麼不使用jQuery真實?看起來像一個奇怪的混合香草JS和jQ ... – elclanrs
比較一個變量對字符串文字(特別是那麼長)可能會流淚。在這些情況下使用布爾或int類型。 –