thinkphp+jquery+ajax前后端交互注冊驗證


thinkphp+jquery+ajax前后端交互注冊驗證,界面如下

 

register.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title>農牧大家評-注冊</title>
    <link rel="stylesheet" href="__PUBLIC__/Css/regis.css" />
    <script type="text/javascript" src='__PUBLIC__/Js/jquery-1.7.2.min.js'></script>
    <script type="text/javascript" src='__PUBLIC__/Js/register.js'/></script>
    <script type="text/javascript">
    //ajax請求地址
var checkAccount = "{:U('checkAccount')}";
var checkUname = "{:U('checkUname')}";
var checkVerify = "{:U('checkVerify')}";
    </script>
</head>
<body>
    <div id='logo'></div>
    <div id='reg-wrap'>
        <form action="{:U('runRegis')}" method='post' name='register'>
            <fieldset>
                <legend><span style="font-weight:bold;font-size:16px;">用戶注冊</span></legend>
                <p>
                    <label for="account">注冊賬號:</label>
                    <input type="text" name='account' id='account' class='input' placeHolder="6~16個字符"  /><span style="margin-left:5px;color:red" id="accountflag"></span>
                </p>
                <p>
                    <label for="pwd">密碼:</label>
                    <input type="password" name='pwd' id='password' placeHolder="6~16個字符" class='input'/><span style="margin-left:5px;color:red" id="passwordflag"></span>
                </p>
<style type="text/css">
     .chushi{
              width:68px;
        height:18px;
        line-height:18px;
        background:#EEEEEE;
        display:inline-block;
        margin-top:3px;
        text-align:center;
     
     
     }
     .power{
              width:68px;
        height:18px;
        line-height:18px;
        background:red;
        display:inline-block;
        margin-top:3px;
        text-align:center;
     }

</style>
                <p>
                    <label for="pwded">密碼強度:</label>
                                                        <span class="pwd-letter">
                                            <span class="chushi"></span>
                                            <span class="chushi"></span>
                                            <span class="chushi"></span>
                                        </span>
                </p>
                <p>
                    <label for="pwded">確認密碼:</label>
                    <input type="password" name='pwded' id="repassword" class='input'/>
                    <span style="margin-left:5px;color:red" id="repasswordflag"></span>
                </p>
                <p>
                    <label for="uname">昵稱:</label>
                    <input type="text"  name='uname' id='uname' placeHolder="3~10個字符" class='input'/>
                    <span style="margin-left:5px;color:red" id="unameflag"></span>
                </p>
                <p>
                    <label for="verify">驗證碼:</label>
                    <input type="text" name='code' class='input' id='code'/>
                    <img src="{:U('verify')}" width='80' height='20' id='code-img'/>
                    <span style="margin-left:5px;color:red" id="codeflag"></span>
                </p>
                <p class='run'>
                    <input type="submit" value='馬上注冊' id='regis'/>
                </p>
            </fieldset>
        </form>
    </div>
</body>
</html>

 register.js

$(function(){

//刷新驗證碼
function changeImg(){
     $("#code-img").attr('src',function(i,v){
          return v+'?'+Math.random();
      });
}

//點擊刷新驗證碼
$("#code-img").click(function(){
          //驗證碼的更換
          changeImg();
    });

//設置錯誤和正確的樣式
function flagError(account){
        $('#'+account).removeClass('valid1');
        $('#'+account+'flag').removeClass('valid2');
        $('#'+account).addClass('error1');
        $('#'+account+'flag').addClass('error2');
}
function flagValid(account){
        $('#'+account).removeClass('error1');
        $('#'+account+'flag').removeClass('error2');
        $('#'+account).addClass('valid1');
        $('#'+account+'flag').addClass('valid2');
}

//驗證賬戶
//設置狀態
var accountflag=false;
function checkAccountjs(oo){
    var patten=/^\w{6,16}$/;
    if(!patten.test(oo.value)){
        accountflag=false;
        flagError('account');
        $('#accountflag').html("賬號必須為6~16位只包含字母,數字,下划線");
        return false;
    }else{        
        //利用Ajax實現用戶名查詢是否存在
        $.ajax({
                            url:checkAccount,
                            data:{'account':oo.value},
                            dataType:'json',
                            type:'post',
                            success:function(msg){
                if(!msg){
                    flagError('account');
                    $('#accountflag').html("賬戶已被占用");
                    return false;
                }else{
                    flagValid('account');
                    $('#accountflag').html('');
                    accountflag=true;
                }
                            }
                        });
    }
}

$('#account').blur(function(){
        //查詢用戶名是否合法
        checkAccountjs(this);
});

//密碼驗證
//設置狀態
var passwordflag=false;
function  checkPassword(oo){
    var patt = /^\w{6,16}$/;
        if(!patt.test(oo.value)){
            flagError('password');
            $('#passwordflag').html('密碼必須為6~16位只包含字母,數字,下划線');
            return false;
        }else{
            flagValid('password');
            $('#passwordflag').html('');
            passwordflag=true;
        }
        
}

//判斷密碼強度
function qiangdu(oo){
        var pwd_letter=$(".pwd-letter span");
          var modes=0;
          var pwd=oo.value;
        if (pwd.length < 6 || pwd.length > 16){
            pwd_letter.eq(modes).removeClass('power').siblings().removeClass('power');
            pwd_letter.eq(modes).addClass('chushi').siblings().addClass('chushi');
        }else{
        if (/\d/.test(pwd)) modes++; //數字
        if (/[a-z]/.test(pwd)) modes++; //小寫
        if (/[A-Z_]/.test(pwd)) modes++; //大寫
              pwd_letter.eq(modes-1).removeClass('chushi').siblings().removeClass('power');
              pwd_letter.eq(modes-1).addClass('power').siblings().addClass('chushi');
          }
}


$('#password').keyup(function(){
        //查詢用戶名是否合法
        checkPassword(this);
        qiangdu(this);
});

//確認密碼一致
//設置狀態
var repasswordflag=false;
function checkRepassword(oo){
    var password = $('#password').val();
        if(password != oo.value){
            if(oo.value.length>0){
            flagError('repassword');
            $('#repasswordflag').html('兩次密碼輸入不一致');
            return false;
            }

        }else{
            if(oo.value.length>0){
            flagValid('repassword');
            $('#repasswordflag').html('');
            repasswordflag=true;
            }

        }
}

$('#repassword').keyup(function(){
        if (this.value.length < 6 || this.value.length > 16){
            return false;
             }
        checkRepassword(this);
});

// //判斷長度
//  function strlen(str) {
//         var len = 0;
//         for (var i = 0; i < str.length; i++) {
//             var c = str.charCodeAt(i);
//             //單字節加1 
//             if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
//                 len++;
//             }
//             else {
//                 len += 1;
//             }
//         }
//         return len;
//     }

//驗證昵稱
//設置狀態
var unameflag=false;
function checkUnamejs(oo){
    var patten=/^[\u4e00-\u9fa5_\w]{3,10}$/;
    if(!patten.test(oo.value)){
        unameflag=false;
        flagError('uname');
        $('#unameflag').html("昵稱必須為3~10位只包含字母,數字,下划線,中文");
        return false;
    }else{        
        //利用Ajax實現用戶名查詢是否存在
        $.ajax({
                            url:checkUname,
                            data:{'uname':oo.value},
                            dataType:'json',
                            type:'post',
                            success:function(msg){
                if(!msg){
                    flagError('uname');
                    $('#unameflag').html("賬戶已被占用");
                    return false;
                }else{
                    flagValid('uname');
                    $('#unameflag').html('');
                    unameflag=true;
                }
                            }
                        });
    }
}

$('#uname').blur(function(){
        //查詢用戶名是否合法
        checkUnamejs(this);
});

//驗證碼
//設置狀態
var codeflag=false;
function checkCode(oo){
    if(oo.value.length!=4){
        flagError('code');
        $('#codeflag').html("驗證碼格式不對");
        return false;
    }
    if (oo.value.length==4) {
        $.ajax({
                            url:checkVerify,
                            data:{'code':oo.value},
                            dataType:'json',
                            type:'post',
                            success:function(msg){
                if(!msg){
                    flagError('code');
                    $('#codeflag').html("驗證碼錯誤,請重新輸入");
                    return false;
                }else{
                    flagValid('code');
                    $('#codeflag').html('');
                    codeflag=true;
                }
                                }
                        });
    }
}

$('#code').keyup(function(){
        checkCode(this);
});

$('#regis').click(function(){
    if (accountflag&&passwordflag&&repasswordflag&&unameflag&&codeflag) {
        return true;
    }else{
        checkAccountjs($('#account')[0]);
        checkPassword($('#password')[0]);
        qiangdu($('#password')[0]);
        checkRepassword($('#repassword')[0]);
        checkUnamejs($('#uname')[0]);
        checkCode($('#code')[0]);
        return accountflag&&passwordflag&&repasswordflag&&unameflag&&codeflag;
    }
    return false;
    
});

});

AccessController.class.php

<?php
namespace Home\Controller;
use Think\Controller;
/**
 * 注冊與登錄控制器
 */
Class AccessController extends Controller {
    /**
     * 登錄頁面
     */
    Public function index () {
        $this->display();
    }



    /**
     * 注冊頁面
     */
    Public function register () {
        $this->display();
    }

    /**
     * 注冊表單處理
     */
    Public function runRegis () {
        //post提交
        if (!IS_POST) {
            $this->error('頁面不存在');
        }

        //驗證碼判斷
        $code = $_POST['code'];
        $verify = new \Think\Verify();
        $verify->reset=false;
        if (!$verify->check($code)) {
            $this->error('驗證碼錯誤');
        }

        //驗證賬戶
        $patten='/^\w{6,16}$/';
        if(!preg_match($patten, $_POST['account'])){
            $this->error('賬戶格式不對');
        }
        $where = array('account' => $account);
        if (D('user')->where($where)->find()) {
            $this->error('賬戶已被占用');
        }

        //驗證密碼格式
        $patten='/^\w{6,16}$/';
        if(!preg_match($patten, $_POST['pwd'])){
            $this->error('密碼格式不對');
        }
        if ($_POST['pwd'] != $_POST['pwded']) {
            $this->error('兩次密碼不一致');
        }

        //驗證昵稱
        $patten='/^[\x{4e00}-\x{9fa5}\w]{3,10}$/u';
        echo $_POST['uname'];
        if(!preg_match($patten, $_POST['uname'])){
            $this->error('昵稱格式不對');
        }
        $uname=$_POST['uname'];
        $where = array('uname' => $uname);
        if (D('userinfo')->where($where)->find()) {
            $this->error('昵稱已被占用');
        }


        //提取POST數據
        $data = array(
            'account' =>I('post.account'),
            'password' =>md5(I('post.pwd')) ,
            'registime' => $_SERVER['REQUEST_TIME'],
            'userinfo' => array(
                'username' => I('post.uname')
                )
            );
        $id = D('UserRelation')->insert($data);
        if ($id) {//插入數據成功后把用戶ID寫SESSION
            session('uid', $id);
            session('uname', $uname);
            //跳轉至首頁
            $this->success('注冊成功,正在為您跳轉...','Home/Index/index');
        } else {
            $this->error('注冊失敗,請重試...');
        }
    }

    /**
     * 獲取驗證碼
     */
    Public function verify() {
        $Verify = new \Think\Verify();
        $Verify->reset = true;
        $Verify->length = 4;
        $Verify->useNoise = false;
        $Verify->entry();
    }

    /**
     * 異步驗證賬號是否已存在
     */
    Public function checkAccount () {
        if (!IS_POST) {
            $this->error('頁面不存在');
        }
        $account =I('post.account');
        $where = array('account' => $account);
        if (D('user')->where($where)->find()) {
            echo 'false';
        } else {
            echo 'true';
        }
    }

    /**
     * 異步驗證昵稱是否已存在
     */
    Public function checkUname () {
        if (!IS_POST) {
            $this->error('頁面不存在');
        }
        $username =I('post.uname');
        $where = array('username' => $username);
        if (D('userinfo')->where($where)->find()) {
            echo 'false';
        } else {
            echo 'true';
        }
    }

    /**
     * 異步驗證驗證碼
     */
    Public function checkVerify () {
        if (!IS_POST) {
            $this->error('頁面不存在');
        }
        $code = I('post.code');
        $verify = new \Think\Verify();
        $verify->reset=false;
        if (!$verify->check($code)) {
            echo 'false';
        } else {
            echo 'true';
        }
    }
}
?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM