有效电子邮件仍然返回false

时间:2014-08-18 23:04:14

标签: javascript php jquery ajax

所以我试图检查一封电子邮件是否有效,我知道我只能使用JS,但我更喜欢我的方式。所以这就是我正在做的事情

//Get data
if(isset($_POST['email'])){
    $email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8')
}
else{
    header('Location: /');
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo 1;
}
else{
    echo 0;
}

我的JS

    $(document).ready(function() {
    //listens for typing on the desired field
    $("#email").keyup(function() {
        //gets the value of the field
        var email = $("#email").val(); 

        //here is where you send the desired data to the PHP file using ajax
        $.post("../classes/validate.php", {email:email},
            function(result) {
                if(result == 1) {
                    //Email is valid
                    console.log("Good");
                }
                else {
                    //Email is invalid
                    console.log("Bad");
                }
            });
     });
});

现在无论我输入什么,它总是返回Bad。即使有效的电子邮件。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

在验证之前,您不应该使用htmlspecialchars()。仅用于演示,即。以HTML格式输出电子邮件时。

答案 1 :(得分:1)

将电子邮件存储为变量后,您立即错过了分号。

//Get data
if(isset($_POST['email'])){
    $email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
}
else{
    header('Location: /');
}
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo 1;
}
else{
    echo 0;
}