【问题标题】:jQuery Validator Plugin - check for existing Username/Email in mysql databasejQuery Validator Plugin - 检查 mysql 数据库中现有的用户名/电子邮件
【发布时间】:2013-11-01 13:51:34
【问题描述】:

我已经成功创建了一个表单,用于提交用户并将其添加到 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();
}
?>

【问题讨论】:

  • 在您的自定义方法中使用 Ajax。
  • @JensonMJohn 自定义验证方法中的简单 Ajax 不起作用,因为 Ajax 是异步的,并且 jQuery.validator 期望返回。

标签: javascript php jquery mysql validation


【解决方案1】:
$.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';
    }
    ?>

【讨论】:

  • 这看起来很棒,感谢您这么快的回复!我不明白为什么额外的“return $("#email").val();”有没有?那不是两次发送电子邮件地址吗? checkUnameEmail.php 还应该包含什么?再次感谢,你不知道我有多感激这个
  • checkUnameEmail.php 您实际上需要检查用户名/电子邮件是否存在。
  • 我用我当前的代码更新了我的问题,我认为你让我更接近了 - 可能只是一件小事导致它无法工作。
  • 您可以在 checkUnameEmail.php 的其他部分和验证器消息部分中执行 echo "false" 添加远程:“E-Mail-Adresse schon registriert”。用于电子邮件。
  • 谢谢简森,我刚看到你的回复。将遥控器的类型从“post”更改为“get”修复了它。它现在可以完美地通知重复的用户名和电子邮件:-) 唯一的问题是无论如何仍然可以提交表单,我将不得不尝试弄清楚这一点。你今天救了一个 n00b 的命,谢谢 Jenson。
【解决方案2】:

js代码

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');
    }
}

【讨论】:

    【解决方案3】:

    对于 WordPress 和 PHP

    最重要的是相反或返回真或假,需要回显'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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多