使用jquery验证插件查找重复的电子邮件

时间:2016-01-25 12:21:45

标签: php jquery mysql validation

我有一个注册页面,我用jquery validation验证所有字段条目。如何使用jquery验证我的表单以检查我的mysql数据库中的重复项?我尝试使用远程方法但是当我输入已经在数据库中的电子邮件时没有任何反应。

sign_up.php

$("#feedbackForm").validate({
    rules: {
        email: {
            required: true,
            email: true,
            remote: "inc/check_email.php"
        }
    },
    messages: {
        email: {
            email: "Insert valid adress",
            required: "Please complete email field",
            remote: "Email is already in use, please change it."
        }
    }
});

/inc/check_email.php

<?php

include('config.php');

$email = $_POST['email'];
$query = mysql_query("SELECT * FROM table WHERE email  = '" . $email . "'");

if (mysql_num_rows($query) > 0) {
    return true;
} else{
    return false;
}

3 个答案:

答案 0 :(得分:1)

来自documentation

  

服务器端响应必须是JSON字符串,对于有效元素必须为“true”,对于无效元素,可以使用默认错误消息为“false”,未定义或null。如果服务器端响应是字符串,例如。 “该名称已被采用,请尝试使用peter123”,此字符串将显示为自定义错误消息,而不是默认值。

所以你需要将你的if改为:

$array = ['email' => 'true'];
if (mysql_num_rows($query) > 0) {
   $array['email'] = 'Email is duplicated';
}

echo json_encode($array);

此外,您应该将数据库引擎更改为pdo或mysqli。不推荐使用Mysql_ *函数。

答案 1 :(得分:0)

查看此网址

http://jqueryvalidation.org/files/demo/ajaxSubmit-integration-demo.html

jQuery(function() {
        $.mockjax({
            url: "login.action",
            response: function(settings) {
                var user = settings.data.match(/user=(.+?)($|&)/)[1],
                    password = settings.data.match(/password=(.+?)($|&)/)[1];
                if (password !== "foobar") {
                    this.responseText = "Your password is wrong (must be foobar).";
                    return;
                }
                this.responseText = "Hi " + user + ", welcome back.";
            },
            responseStatus: 200,
            responseTime: 500
        });

        // show a simple loading indicator
        var loader = jQuery('<div id="loader"><img src="images/loading.gif" alt="loading..."></div>')
            .css({
                position: "relative",
                top: "1em",
                left: "25em",
                display: "inline"
            })
            .appendTo("body")
            .hide();
        jQuery().ajaxStart(function() {
            loader.show();
        }).ajaxStop(function() {
            loader.hide();
        }).ajaxError(function(a, b, e) {
            throw e;
        });

        var v = jQuery("#form").validate({
            submitHandler: function(form) {
                jQuery(form).ajaxSubmit({
                    target: "#result"
                });
            }
        });

        jQuery("#reset").click(function() {
            v.resetForm();
        });
    });

答案 2 :(得分:0)

该插件期待JSON,谢谢大家。

if (mysql_num_rows($query) > 0) {
echo json_encode(FALSE);
} else{
echo json_encode(TRUE); 
}
相关问题