1. 程式人生 > >jQuery Validator外掛-檢測使用者是否已經存在

jQuery Validator外掛-檢測使用者是否已經存在

前言

採用jQuery Validator外掛對使用者註冊進行驗證時,我們需要檢測該使用者是否已經被註冊。可以有兩種方法。

方法一:

在additional-methods.js檔案中新增自定義驗證,並引入到html檔案裡:

$.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;
        }
    });

}, '');

 方法二:

直接用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('[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]');

    $requestedEmail  = $_REQUEST['email'];

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