jQuery Validator插件 - 检查mysql数据库中的现有用户名/电子邮件

时间:2013-10-23 10:27:36

标签: javascript php jquery mysql validation

我已经成功创建了一个表单,提交并将用户添加到mysql数据库,并且使用'jQuery Validator' plugin进行表单验证对于除了检查用户名是否已经存在于数据库中之外的所有内容都非常有用...

我刚刚花了大约8个小时阅读并尝试找出一种方法来使用'jQuery Validator'插件定义一个新方法。我似乎无法理解如何检查数据库中输入的用户名或电子邮件,并使用jQuery返回它是否已经存在。

我的代码:

<script src="../assets/js/main.js"></script>
<script src="../assets/js/ajax.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<!-- FORM VALIDATION -->
<script type="text/javascript">


    jQuery.validator.addMethod("checkExists", 
function(value, element) {
    //No idea what to call here
}, 
"Username already exists."
);


        //<![CDATA[
        $(window).load(function(){
        $("form").validate({
        rules: {
            username: {minlength: 3, required: true, checkExists: true},
            email: {email: true, required: true},
            pass1: {minlength: 3, required: true},
            pass2: {minlength: 3, required: true, equalTo: "#pass1"},
            country: {required: true},
            tandc: {required: true},
        },
        messages: {
        username:   {required: "You need to enter a Username."},
        email:      {required: "You need to enter an Email Address."},
        pass1:      {required: "You need to enter a Password."},
        pass2:      {required: "You need to enter your password again.", equalTo: "Your passwords don't match."},
        country:    {required: "You need to tell us where you live."},
        tandc:      {required: "You need to read and agree to the Terms and Conditions to use CGE."}
        },


        showErrors: function(errorMap, errorList) {
        $.each(this.successList, function(index, value) {
        return $(value).popover("hide");
        });
        return $.each(errorList, function(index, value) {
        var _popover;
        console.log(value.message);
        _popover = $(value.element).popover({
        trigger: "manual",
        placement: "right",
        content: value.message,
        template: "<div class=\"popover\"><div class=\"arrow\"></div><div class=\"popover-inner\"><div class=\"popover-content\"><p></p></div></div></div>"
        });
        _popover.data("popover").options.content = value.message;
        return $(value.element).popover("show");
        });
        }
        });
        });//]]>
</script>

如果有人聪明可以请修改我的代码以告诉我应该怎么做,这将是一个很大的帮助 - 我觉得我要发疯了!

提前致谢,迫不及待地想看到解决方案: - )


编辑 - 这是我当前的代码

似乎根本没有发生任何事情,我觉得我离我更近了:

当前代码:

signup.php

    $(window).load(function(){
            $("form").validate({
            rules: {
                username: {minlength: 3, required: true},
                email: {email: true, required: true, remote: {url: "./validation/checkUnameEmail.php", type : "post"}},
                pass1: {minlength: 3, required: true},
                pass2: {minlength: 3, required: true, equalTo: "#pass1"},
                country: {required: true},
                tandc: {required: true}
},

checkUnameEmail.php

<?php
    include_once(".../php_includes/db_conx.php");
    $email = urldecode($_POST['email']);
    $result = mysqli_query($db_conx, "SELECT * FROM users WHERE email = '$email' LIMIT 1;");
    $num = mysqli_num_rows($result);
    if($num == 0){
        echo "true";
    } else {
        echo "E-Mail-Adresse schon registriert.";
    }
    mysqli_close($db_conx);
?>

* db_conx.php *

<?php
$db_conx = mysqli_connect("localhost", "root", "root", "membership");
//Evlauate the connection
if (mysqli_connect_errno()){
    echo mysqli_connect_error();
    exit();
}
?>

3 个答案:

答案 0 :(得分:16)

$.validator.addMethod("checkExists", function(value, element)
{
    var inputElem = $('#register-form :input[name="email"]'),
        data = { "emails" : inputElem.val() },
        eReport = ''; //error report

    $.ajax(
    {
        type: "POST",
        url: validateEmail.php,
        dataType: "json",
        data: data, 
        success: function(returnData)
        {
            if (returnData!== 'true')
            {
              return '<p>This email address is already registered.</p>';
            }
            else
            {
               return true;
            }
        },
        error: function(xhr, textStatus, errorThrown)
        {
            alert('ajax loading error... ... '+url + query);
            return false;
        }
    });

}, '');

您可以使用远程方法来进行远程检查: http://docs.jquery.com/Plugins/Validation/Methods/remote

例如

    $("#yourFormId").validate({
            rules: {
                email: {
                    required: true,
                    email: true,
                    remote: {
                        url: "checkUnameEmail.php",
                        type: "post"
                     }
                }
            },
            messages: {
                email: {
                    required: "Please Enter Email!",
                    email: "This is not a valid email!",
                    remote: "Email already in use!"
                }
            }
        });

checkUnameEmail.php //例如。

    <?php
    $registeredEmail = array('jenson1@jenson.in', 'jenson2@jenson.in', 'jenson3@jenson.in', 'jenson4@jenson.in', 'jenson5@jenson.in');

    $requestedEmail  = $_REQUEST['email'];

    if( in_array($requestedEmail, $registeredEmail) ){
        echo 'false';
    }
    else{
        echo 'true';
    }
    ?>

答案 1 :(得分:1)

js code

username: {
        required: true,
        minlength: 5,
        remote: '/userExists'
       },

用于检查是否存在的Php代码并返回消息

public function userExists()
{
    $user = User::all()->lists('username');
    if (in_array(Input::get('username'), $user)) {
        return Response::json(Input::get('username').' is already taken');
    } else {
        return Response::json(Input::get('username').' Username is available');
    }
}

答案 2 :(得分:0)

对于WordPress和PHP

最重要的是,或者返回true或false,需要回显“ true”或“ false”

  

jQuery或JS

   email: {
     required: true,
     minlength: 6,
     email: true,
     remote:{
        url : 'your ajax url',
        data: { 
                'action': 'is_user_exist',
              },
        },
   },
  

WordPress或PHP后端代码

在后端,您将通过GET方法自动获取字段的值。

/*
 *@ Check user exists or not
 */
if( !function_exists('is_user_exists_ajax_function') ):
    function is_user_exists_ajax_function() {
        $email = $_GET['email'];
        if( empty($email) && is_email($email) ):
            wp_send_json_error( new \WP_Error( 'Bad Request' ) );
        endif;

        $is_email = email_exists( $email );

        if($is_email):
            echo 'false';
        else:
            echo 'true';
        endif;

        wp_die();
    }
    add_action( 'wp_ajax_is_user_exist', 'is_user_exists_ajax_function' ); 
    add_action( 'wp_ajax_nopriv_is_user_exist', 'is_user_exists_ajax_function' ); 
endif;