gpt4 book ai didi

php - 验证 - 如果语句不起作用

转载 作者:行者123 更新时间:2023-11-28 16:07:51 25 4
gpt4 key购买 nike

我正在尝试使用 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>

有谁知道为什么会这样吗?我真的很困惑。

最佳答案

问题是你在 PHP 中 echo 的是

That email address is already in use. If you have created an account, <a>Login</a>

你在 JavaScript 中检查的是

That email address is already in use. If you have created an account, <a href="../login.php">Login</a>

即它们不一样...

我建议您返回 1 (true) 或 0 (false),然后使用 JavaScript 输出文本..类似于

if (email_exists($email) === true) {
echo('0');
} else {
echo('1');
}

那么你的 JavaScript 会是这样的

if ($.trim(data) == '0') {
document.getElementById("email").style.border = "3px solid red";
document.getElementById('email_error').style.display = 'block';
$('div#email_error').text('That email address is already in use. If you have created an account,<a href="../login.php">Login</a>');
} else {
document.getElementById("email").style.border = "3px solid #33FF33";
document.getElementById('email_error').style.display = 'none';
}

关于php - 验证 - 如果语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14142240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com