PHP+jQuery 注冊模塊開發


/*
******* 環境: Apache2.2.8 + PHP5.2.6 + MySQL5.0.51b + jQuery-1.8.3.min.js *******
******* 其他組件:Zend_mail( Zend_framework 1.11.11 )
******* Date:2014-09-25
******* Author:小dee
******* Blog:http://www.cnblogs.com/dee0912/
*/

寫了一個簡單的PHP+jQuery注冊模塊,需要填寫的欄目包括用戶名、郵箱、密碼、重復密碼和驗證碼,其中每個欄目需要具備的功能和要求如下圖:

在做這個模塊的時候,很大程度上借鑒了網易注冊( http://reg.163.com/reg/reg.jsp?product=urs )的功能和樣式。但網易對於每個欄目的判斷的做法是:在輸入文字時,並不給出任何實時的檢測結果,而在這個欄目失去焦點時,才把檢測的結果展示出來,這種做法我認為會使用戶在輸入時視覺上比較統一,看到的是關於該欄目要求的提示,不會出現其他信息的打擾,但同時也不會得到正在輸入的字符的檢測提示。所以在做這個功能的時候,我把我自認為需要實時提示的一些信息做了相應的加強,比如用戶名長度超過限制和密碼的長度以及強弱,並且給郵箱的大寫鎖定做了簡單的判斷。

注:表單的提交按鈕type為button而不是submit,因此所有欄目的回車( keydown )都統一設置為將焦點移至下一個欄目,除了最后一個欄目驗證碼,在驗證碼欄目使用回車( keydown )會觸發提交事件。

 

功能分析

用戶名欄目:

流程

①頁面加載完即獲得焦點,獲得焦點時出現初始說明文字;

②鼠標點擊用戶名輸入框,出現初始說明文字;

③輸入字符,即時提示是否符合長度要求;

④失去焦點時首先判斷是否為空,為空時提示不能為空;非空且長度滿足要求時,開始檢測用戶名是否被注冊;

⑤用戶名已被注冊,給出提示,如果沒有注冊,則提示可以注冊;

⑥再次獲得焦點時,不論輸入框中是否有輸入,或是否輸入符合規定,都出現初始說明文字

⑦回車時將焦點移至郵箱欄目

如圖:

細節

可以使用任意字符,並且字數限制為:中文長度不超過7個漢字,英文、數字或符號長度不超過14個字母、數字或符號(類似豆瓣注冊https://www.douban.com/accounts/register),即不超過14個字符

關於占位符(字符長度),一個漢字的占位符是2,一個英文(數字)的占位符是1,可以用php語句來計算字符的長度

1 <?php
2 //php.ini開啟了php_mbstring.dll擴展
3 $str="博客園小dee";
4  
5 echo (strlen($str)+mb_strlen($str,'utf-8'))/2;

輸出:11

而strlen($str) 輸出的是15:4*3+3,漢字在utf-8編碼下占3個字節,英文占1個,

mb_strlen($str,'utf-8') 輸出的是7:一個漢字的長度是1,

如果用jquery的length來輸出這個字符串,alert($("#uname").val().length),則會得到長度7,

這點要注意。

同時用戶名兩端不能含有空格,在檢測以及注冊時,程序會自動過濾用戶名兩端的空格。

 

register.html 用戶名欄目的HTML代碼片段:

1 <!-- 用戶名 -->        
2 <div class="ipt fipt">
3     <input type="text" name="uname" id="uname" value="" placeholder="輸入用戶名"  autocomplete="off" />
4     <!--提示文字-->
5     <span id="unamechk"></span>
6 </div>

register.js公用部分的js代碼:

 1 $(function(){
 2     
 3     //說明文字
 4     function notice(showMsg,noticeMsg){            
 5         showMsg.html(noticeMsg).attr("class","notice");
 6     }
 7     //顯示錯誤信息
 8     function error(showMsg,errorMsg){    
 9         showMsg.html(errorMsg).attr("class","error");
10     }    
11     //顯示正確信息
12     function success(showMsg,successMsg){    
13         showMsg.html(successMsg)                
14                        .css("height","20px")
15                        .attr("class","success");
16     }
17 
18     //計算字符長度
19     function countLen(value){
20     
21         var len = 0; 
22         for (var i = 0; i < value.length; i++) { 
23             if (value[i].match(/[^\x00-\xff]/ig) != null) 
24             len += 2; 
25             else 
26             len += 1; 
27         } 
28         return len;
29     }                     
30 
31     //......
32 )};

 register.js用戶名部分的js代碼:

 1 //檢測用戶名長度
 2 function unameLen(value){
 3     
 4         var showMsg = $("#unamechk");
 5 
 6         /* (strlen($str)+mb_strlen($str))/2 可得出限制字符長度的上限,
 7         *  例如:$str為7個漢字:"博客園記錄生活",利用上面的語句可得出14,
 8         *  同樣,14個英文,利用上面的語句同樣能得出字符長度為14
 9         */
10         if(countLen(value) > 14){
11                         
12             var errorMsg = '用戶名長度不能超過14個英文或7個漢字';
13             error(showMsg,errorMsg);        
14         }else if(countLen(value) == 0){
15         
16             var noticeMsg = '用戶名不能為空';
17             notice(showMsg,noticeMsg);
18         }else{
19 
20             var successMsg = '長度符合要求';
21             success(showMsg,successMsg);
22         }
23 
24         return countLen(value);
25     }
26 
27     //用戶名
28     unameLen($("#uname").val());
29     
30     $("#uname").focus(function(){
31     
32                     var noticeMsg = '中英文均可,最長為14個英文或7個漢字';
33                     notice($("#unamechk"),noticeMsg);
34                 })
35                .click(function(){
36                     
37                     var noticeMsg = '中英文均可,最長為14個英文或7個漢字';
38                     notice($("#unamechk"),noticeMsg);
39                 })
40                .keyup(function(){
41     
42                     unameLen(this.value);
43                 }).keydown(function(){
44                 
45                     //把焦點移至郵箱欄目
46                     if(event.keyCode == 13){
47                         
48                         $("#uemail").focus();
49                     }
50                 })
51                 .blur(function(){
52                 
53                     if($("#uname").val()!="" && unameLen(this.value)<=14 && unameLen(this.value)>0){
54                         //檢測中
55                         $("#unamechk").html("檢測中...").attr("class","loading");
56                         //ajax查詢用戶名是否被注冊
57                         $.post("./../chkname.php",{
58                         
59                             //要傳遞的數據
60                             uname : $("#uname").val()
61                         },function(data,textStatus){
62                             
63                             if(data == 0){
64                             
65                                 var successMsg = '恭喜,該用戶名可以注冊';
66                                 $("#unamechk").html(successMsg).attr("class","success");
67 
68                                 //設置參數
69                                 nameval = true;
70                             }else if(data == 1){
71                             
72                                 var errorMsg = '該用戶名已被注冊';
73                                 error($("#unamechk"),errorMsg);
74                             }else{
75                             
76                                 var errorMsg = '查詢出錯,請聯系網站管理員';
77                                 error($("#unamechk"),errorMsg);
78                             }
79                         });
80                     }else if(unameLen(this.value)>14){
81                     
82                         var errorMsg = '用戶名長度不能超過14個英文或7個漢字';
83                         error($("#unamechk"),errorMsg);
84                     }else{
85                     
86                         var errorMsg = '用戶名不能為空';
87                         error($("#unamechk"),errorMsg);
88                     }
89 });
90 
91 //加載后即獲得焦點
92 $("#uname").focus();

checkname.php代碼:

 1 <?php
 2 
 3     header("charset=utf-8");
 4 
 5     require_once("conn/conn.php");
 6 
 7     if(isset($_POST['uname']) && $_POST['uname']!=""){
 8     
 9         $uname = trim(addslashes($_POST['uname']));
10     }
11 
12     $sql = "select uname from user where uname='".$uname."'";
13     
14     if($conne->getRowsNum($sql) == 1){
15     
16         $state = 1;
17     }else if($conne->getRowsNum($sql) == 0){
18     
19         $state = 0;
20     }else{
21 
22         echo $conne->msg_error();
23     }
24 
25     echo $state;

提示文字( Chrome下 )

①初始獲得焦點、再次獲得焦點或點擊時

 

       

 

②輸入時實時檢測長度

       

   

 

③刪除至空且未失去焦點時,使用藍色圖標提示不能為空——用戶在輸入時看起來不突兀

       

 

④失去焦點且不為空,檢測是否被注冊( 非常短暫,一閃而過 )

     

⑤失去焦點時為空、可以注冊、已被注冊時

       

       

       

用戶名分析至此完畢。

 

郵箱欄目:

流程

①當欄目獲得焦點或者點擊時不論欄目為空、填寫正確或者填寫錯誤時都出現說明文字;

②用戶輸入時出現下拉菜單顯示多種郵件后綴供用戶選擇;

失去焦點時首先判斷郵箱格式是否正確,如果正確則檢測郵箱是否被注冊 ;

④在使用回車選擇下拉菜單時,將自動填充郵箱欄目;沒有出現下拉菜單時,將焦點移至密碼欄目

如圖:

register.html 郵箱欄目HTML代碼片段:

1 <!-- email -->            
2 <div class="ipt">
3     <input type="text" name="uemail" id="uemail" value="" placeholder="常用郵箱地址" />
4     <span id="uemailchk"></span>
5     <ul class="autoul"></ul>
6 </div>    

下拉功能emailup.js同之前的博文《jQuery實現下拉提示且自動填充的郵箱》,略有修改,注意用回車( keydown和keyup事件 )在不同情況下觸發的不同動作:

  1 $(function(){
  2     
  3     //初始化郵箱列表
  4     var mail = new Array("sina.com","126.com","163.com","gmail.com","qq.com","hotmail.com","sohu.com","139.com","189.cn","sina.cn");
  5 
  6     //把郵箱列表加入下拉
  7     for(var i=0;i<mail.length;i++){
  8     
  9         var $liElement = $("<li class=\"autoli\"><span class=\"ex\"></span><span class=\"at\">@</span><span class=\"step\">"+mail[i]+"</span></li>");
 10 
 11         $liElement.appendTo("ul.autoul");
 12     }
 13 
 14     //下拉菜單初始隱藏
 15     $(".autoul").hide();
 16     
 17     //在郵箱輸入框輸入字符
 18     $("#uemail").keyup(function(){
 19      
 20         if(event.keyCode!=38 && event.keyCode!=40 && event.keyCode!=13){
 21 
 22             //菜單展現,需要排除空格開頭和"@"開頭
 23             if( $.trim($(this).val())!="" && $.trim(this.value).match(/^@/)==null ) {
 24 
 25                 $(".autoul").show();
 26                 //修改
 27                 $(".autoul li").show();
 28 
 29                 //同時去掉原先的高亮,把第一條提示高亮
 30                 if($(".autoul li.lihover").hasClass("lihover")) {
 31                     $(".autoul li.lihover").removeClass("lihover");
 32                 }
 33                 $(".autoul li:visible:eq(0)").addClass("lihover");
 34             }else{//如果為空或者"@"開頭
 35                 $(".autoul").hide();
 36                 $(".autoul li:eq(0)").removeClass("lihover");
 37             }
 38 
 39             //把輸入的字符填充進提示,有兩種情況:1.出現"@"之前,把"@"之前的字符進行填充;2.出現第一次"@"時以及"@"之后還有字符時,不填充
 40             //出現@之前
 41             if($.trim(this.value).match(/[^@]@/)==null){//輸入了不含"@"的字符或者"@"開頭
 42                 if($.trim(this.value).match(/^@/)==null){
 43 
 44                     //不以"@"開頭
 45                     //這里要根據實際html情況進行修改
 46                     $(this).siblings("ul").children("li").children(".ex").text($(this).val());
 47                 }
 48             }else{
 49 
 50                 //輸入字符后,第一次出現了不在首位的"@"
 51                 //當首次出現@之后,有2種情況:1.繼續輸入;2.沒有繼續輸入
 52                 //當繼續輸入時
 53                 var str = this.value;//輸入的所有字符
 54                 var strs = new Array();
 55                 strs = str.split("@");//輸入的所有字符以"@"分隔
 56                 $(".ex").text(strs[0]);//"@"之前輸入的內容
 57                 var len = strs[0].length;//"@"之前輸入內容的長度
 58                 if(this.value.length>len+1){
 59 
 60                     //截取出@之后的字符串,@之前字符串的長度加@的長度,從第(len+1)位開始截取
 61                     var strright = str.substr(len+1);
 62 
 63                     //正則屏蔽匹配反斜杠"\"
 64                     if(strright.match(/[\\]/)!=null){
 65                         strright.replace(/[\\]/,"");
 66                         return false;
 67                     }
 68                  
 69                     //遍歷li
 70                     $("ul.autoul li").each(function(){
 71 
 72                         //遍歷span
 73                         //$(this) li
 74                         $(this).children("span.step").each(function(){
 75 
 76                             //@之后的字符串與郵件后綴進行比較
 77                             //當輸入的字符和下拉中郵件后綴匹配並且出現在第一位出現
 78                             //$(this) span.step
 79                             if($("ul.autoul li").children("span.step").text().match(strright)!=null && $(this).text().indexOf(strright)==0){
 80                                 
 81                                 //class showli是輸入框@后的字符和郵件列表對比匹配后給匹配的郵件li加上的屬性
 82                                 $(this).parent().addClass("showli");
 83                                 //如果輸入的字符和提示菜單完全匹配,則去掉高亮和showli,同時提示隱藏
 84                                 
 85                                 if(strright.length>=$(this).text().length){
 86                                         
 87                                     $(this).parent().removeClass("showli").removeClass("lihover").hide();
 88                                 }
 89                             }else{
 90                                 $(this).parent().removeClass("showli");
 91                             }
 92                             if($(this).parent().hasClass("showli")){
 93                                 $(this).parent().show();
 94                                 $(this).parent("li").parent("ul").children("li.showli:eq(0)").addClass("lihover");
 95                             }else{
 96                                 $(this).parent().hide();
 97                                 $(this).parent().removeClass("lihover");
 98                             }
 99                         });
100                     });
101 
102                     //修改
103                     if(!$(".autoul").children("li").hasClass("showli")){
104 
105                         $(".autoul").hide();
106                     }
107                 }else{
108                     //"@"后沒有繼續輸入時
109                     $(".autoul").children().show();
110                     $("ul.autoul li").removeClass("showli");
111                     $("ul.autoul li.lihover").removeClass("lihover");
112                     $("ul.autoul li:eq(0)").addClass("lihover");
113                 }
114             }
115         }//有效輸入按鍵事件結束
116 
117         if(event.keyCode == 8 || event.keyCode == 46){
118      
119           $(this).next().children().removeClass("lihover");
120           $(this).next().children("li:visible:eq(0)").addClass("lihover");
121         }//刪除事件結束  
122         
123        if(event.keyCode == 38){
124          //使光標始終在輸入框文字右邊
125           $(this).val($(this).val());
126        }//方向鍵↑結束
127         
128        if(event.keyCode == 13){
129         
130             //keyup時只做菜單收起相關的動作和去掉lihover類的動作,不涉及焦點轉移
131             $(".autoul").hide();
132             $(".autoul").children().hide();
133             $(".autoul").children().removeClass("lihover");          
134        }
135     });    
136     
137     $("#uemail").keydown(function(){
138 
139         if(event.keyCode == 40){
140 
141             //當鍵盤按下↓時,如果已經有li處於被選中的狀態,則去掉狀態,並把樣式賦給下一條(可見的)li
142             if ($("ul.autoul li").is(".lihover")) {
143 
144                 //如果還存在下一條(可見的)li的話
145                 if ($("ul.autoul li.lihover").nextAll().is("li:visible")) {
146 
147                     if ($("ul.autoul li.lihover").nextAll().hasClass("showli")) {
148 
149                         $("ul.autoul li.lihover").removeClass("lihover")
150                                 .nextAll(".showli:eq(0)").addClass("lihover");
151                     } else {
152 
153                         $("ul.autoul li.lihover").removeClass("lihover").removeClass("showli")
154                                 .next("li:visible").addClass("lihover");
155                         $("ul.autoul").children().show();
156                     }
157                 } else {
158 
159                     $("ul.autoul li.lihover").removeClass("lihover");
160                     $("ul.autoul li:visible:eq(0)").addClass("lihover");
161                 }
162             } 
163         }
164 
165         if(event.keyCode == 38){
166 
167             //當鍵盤按下↓時,如果已經有li處於被選中的狀態,則去掉狀態,並把樣式賦給下一條(可見的)li
168             if($("ul.autoul li").is(".lihover")){
169 
170                 //如果還存在上一條(可見的)li的話
171                 if($("ul.autoul li.lihover").prevAll().is("li:visible")){
172 
173 
174                     if($("ul.autoul li.lihover").prevAll().hasClass("showli")){
175 
176                         $("ul.autoul li.lihover").removeClass("lihover")
177                                 .prevAll(".showli:eq(0)").addClass("lihover");
178                     }else{
179 
180                         $("ul.autoul li.lihover").removeClass("lihover").removeClass("showli")
181                                 .prev("li:visible").addClass("lihover");
182                         $("ul.autoul").children().show();
183                     }
184                 }else{
185 
186                     $("ul.autoul li.lihover").removeClass("lihover");
187                     $("ul.autoul li:visible:eq("+($("ul.autoul li:visible").length-1)+")").addClass("lihover");
188                 }
189             }else{
190 
191                 //當鍵盤按下↓時,如果之前沒有一條li被選中的話,則第一條(可見的)li被選中
192                 $("ul.autoul li:visible:eq("+($("ul.autoul li:visible").length-1)+")").addClass("lihover");
193             }
194         } 
195 
196         if(event.keyCode == 13){                            
197 
198             //keydown時完成的兩個動作 ①填充 ②判斷下拉菜單是否存在,如果不存在則焦點移至密碼欄目。注意下拉菜單的收起動作放在keyup事件中。即當從下拉菜單中選擇郵箱的時候按回車不會觸發焦點轉移,而選擇完畢菜單收起之后再按回車,才會觸發焦點轉移事件
199             if($("ul.autoul li").is(".lihover")) {
200 
201                 $("#uemail").val($("ul.autoul li.lihover").children(".ex").text() + "@" + $("ul.autoul li.lihover").children(".step").text());
202             }
203 
204             //把焦點移至密碼欄目
205             if($(".autoul").attr("style") == "display: none;"){
206     
207                 $("#upwd").focus();
208             }
209         }
210     });
211 
212     
213     //把click事件修改為mousedown,避免click事件時短暫的失去焦點而觸發blur事件
214     $(".autoli").mousedown(function(){
215  
216         $("#uemail").val($(this).children(".ex").text()+$(this).children(".at").text()+$(this).children(".step").text());
217         $(".autoul").hide();
218         
219         //修改
220         $("#uemail").focus();
221     }).hover(function(){
222 
223         if($("ul.autoul li").hasClass("lihover")){
224 
225             $("ul.autoul li").removeClass("lihover");
226         }
227         $(this).addClass("lihover");
228     });
229 
230     $("body").click(function(){
231 
232         $(".autoul").hide();
233     });
234 });
View Code 

register.js郵箱代碼片段:

//郵箱下拉js單獨引用emailup.js
$("#uemail").focus(function(){
    
                    var noticeMsg = '用來登陸網站,接收到激活郵件才能完成注冊';
                    notice($("#uemailchk"),noticeMsg);
                })
                .click(function(){
    
                    var noticeMsg = '用來登陸網站,接收到激活郵件才能完成注冊';
                    notice($("#uemailchk"),noticeMsg);
                })
                .blur(function(){
                
                    if(this.value!="" && this.value.match(/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/)!=null){
                    
                        //檢測是否被注冊
                        $("#uemailchk").html("檢測中...").attr("class","loading");
                        //ajax查詢用戶名是否被注冊
                        $.post("./../chkemail.php",{
                        
                            //要傳遞的數據
                            uemail : $("#uemail").val()
                        },function(data,textStatus){
                            
                            if(data == 0){
                            
                                var successMsg = '恭喜,該郵箱可以注冊';
                                $("#uemailchk").html(successMsg).attr("class","success");

                                emailval = true;
                            }else if(data == 1){
                            
                                var errorMsg = '該郵箱已被注冊';
                                error($("#uemailchk"),errorMsg);
                            }else{
                            
                                var errorMsg = '查詢出錯,請聯系網站管理員';
                                error($("#uemailchk"),errorMsg);
                            }
                        });
                    }else if(this.value == ""){
                    
                        var errorMsg = '郵箱不能為空';
                        error($("#uemailchk"),errorMsg);
                    }else{
                    
                        var errorMsg = '請填寫正確的郵箱地址';
                        $("#uemailchk").html(errorMsg).attr("class","error");
                    }
});

 提示文字( Chrome下 )

①獲得焦點時、點擊時

②輸入時

③失去焦點為空、格式錯誤、已被注冊、可以注冊時分別為

 郵箱功能至此結束。

 

密碼欄目:

要求

①6-16個個字符,區分大小寫(參考豆瓣和網易)

②密碼不能為同一字符

③實時提示是否符合要求以及判斷並顯示密碼強度,:

  1.輸入時如果為空(刪除時)則用藍色符號提示不能為空,超過長度時用紅色符號

  2.密碼滿足長度但是為相同字符的組合時:密碼太簡單,請嘗試數字、字母和下划線的組合

  3.密碼強度判斷有多種規則,有直接依據長度和組合規則作出判斷,也有給每種長度和組合設置分數,通過驗證實際密碼的情況計算出最后分數來判斷強弱。在這個模塊中采用比較簡單的一種形式,也是網易注冊采用的方法:

     密碼滿足長度且全部為不同字母、全部為不同數字或全部為不同符號時為弱:弱:試試字母、數字、符號混搭

     密碼滿足長度且為數字、字母和符號任意兩種組合時為中

     密碼滿足長度且為數字、字母和符號三種組合時為強

④輸入時大寫提示

如圖:

register.html 密碼欄目HTML代碼片段:

1 <div class="ipt">
2     <input type="password" name="upwd" id="upwd" value="" placeholder="設置密碼" />
3     <div class="upwdpic">
4        <span id="upwdchk"></span>
5        <img id="pictie" />
6     </div>
7 </div>

register.js密碼代碼片段:

  1 function noticeEasy(){
  2     
  3         //密碼全部為相同字符或者為123456,用於keyup時的notice
  4         var noticeMsg = '密碼太簡單,請嘗試數字、字母和下划線的組合';
  5         return notice($("#upwdchk"),noticeMsg);
  6     }
  7 
  8     function errorEasy(){
  9     
 10         //密碼全部為相同字符或者為123456,用於blur時的error
 11         var errorMsg = '密碼太簡單,請嘗試數字、字母和下划線的組合';
 12         return error($("#upwdchk"),errorMsg);
 13     }
 14     
 15     //檢測密碼長度函數
 16     //檢測密碼長度
 17     function upwdLen(value,func){
 18     
 19         var showMsg = $("#upwdchk");
 20 
 21         if(countLen(value) > 16){
 22                         
 23             var errorMsg = '密碼不能超過16個字符';
 24             error(showMsg,errorMsg);
 25             
 26             $("#pictie").hide();
 27         }else if(countLen(value) < 6){
 28         
 29             //使用notice更加友好
 30             var noticeMsg = '密碼不能少於6個字符';
 31             notice(showMsg,noticeMsg);
 32 
 33             $("#pictie").hide();
 34         }else if(countLen(value) == 0){
 35         
 36             //使用notice更加友好
 37             var noticeMsg = '密碼不能為空';
 38             notice(showMsg,noticeMsg);
 39 
 40             $("#pictie").hide();
 41         }else{
 42         
 43             upwdStrong(value,func);//如果長度不成問題,則調用檢測密碼強弱
 44         }
 45 
 46         return countLen(value);//返回字符長度
 47     }
 48 
 49     //檢測密碼強弱
 50     function upwdStrong(value,func){
 51     
 52         var showMsg = $("#upwdchk");
 53 
 54         if(value.match(/^(.)\1*$/)!=null || value.match(/^123456$/)){
 55         
 56             //密碼全部為相同字符或者為123456,調用函數noticeEasy或errorEasy
 57             func;
 58         }else if(value.match(/^[A-Za-z]+$/)!=null || value.match(/^\d+$/)!=null || value.match(/^[^A-Za-z0-9]+$/)!=null){
 59 
 60             //全部為相同類型的字符為弱
 61             var successMsg = '弱:試試字母、數字、符號混搭';
 62             success(showMsg,successMsg);
 63 
 64             //插入強弱條
 65             $("#pictie").show().attr("src","images/weak.jpg");
 66 
 67             pwdval = true;
 68 
 69         }else if(value.match(/^[^A-Za-z]+$/)!=null || value.match(/^[^0-9]+$/)!=null || value.match(/^[a-zA-Z0-9]+$/)!=null){
 70         
 71             //任意兩種不同類型字符組合為中強( 數字+符號,字母+符號,數字+字母 )
 72             var successMsg = '中強:試試字母、數字、符號混搭';
 73             success(showMsg,successMsg);
 74 
 75             $("#pictie").show().attr("src","images/normal.jpg");
 76 
 77             pwdval = true;
 78         }else{
 79         
 80             //數字、字母和符號混合
 81             var successMsg = '強:請牢記您的密碼';
 82             success(showMsg,successMsg);
 83 
 84             $("#pictie").show().attr("src","images/strong.jpg");
 85 
 86             pwdval = true;
 87         }
 88     }
 89     
 90     $upper = $("<div id=\"upper\">大寫鎖定已打開</div>");
 91     
 92     $("#upwd").focus(function(){
 93     
 94                     var noticeMsg = '6到16個字符,區分大小寫';
 95                     notice($("#upwdchk"),noticeMsg);
 96 
 97                     $("#pictie").hide();
 98             })
 99              .click(function(){
100             
101                     var noticeMsg = '6到16個字符,區分大小寫';
102                     notice($("#upwdchk"),noticeMsg);
103 
104                     $("#pictie").hide();
105             }).keydown(function(){
106             
107                     //把焦點移至郵箱欄目
108                     if(event.keyCode == 13){
109                         
110                         $("#rupwd").focus();
111                     }
112             })
113              .keyup(function(){
114              
115                     //判斷大寫是否開啟
116                     //輸入密碼的長度
117                     var len = this.value.length;                    
118                     if(len!=0){
119 
120                         //當輸入的最新以為含有大寫字母時說明開啟了大寫鎖定
121                         if(this.value[len-1].match(/[A-Z]/)!=null){
122                         
123                             //給出提示
124                             $upper.insertAfter($(".upwdpic"));
125                         }else{
126                         
127                             //移除提示
128                             $upper.remove();
129                         }
130                     }else{
131                     
132                         //當密碼框為空時移除提示
133                         if($upper){
134                         
135                             $upper.remove();
136                         }
137                     }//判斷大寫開啟結束
138             
139                     //判斷長度及強弱
140                     upwdLen(this.value,noticeEasy());    
141              })
142              //keyup事件結束
143                .blur(function(){
144                
145                     upwdLen(this.value,errorEasy());
146                     //upwdLen函數中部分提示使用notice是為了keyup事件中不出現紅色提示,而blur事件中則需使用error標紅
147                     if(this.value == ""){
148                     
149                         var errorMsg = '密碼不能為空';
150                         error($("#upwdchk"),errorMsg);
151 
152                         $("#pictie").hide();
153                     }else if(countLen(this.value)<6){
154                     
155                         var errorMsg = '密碼不能少於6個字符';
156                         error($("#upwdchk"),errorMsg);
157 
158                         $("#pictie").hide();
159                     }
160 });

大寫鎖定的思路是:判斷輸入的字符的最新一位是否是大寫字母,如果是大寫字母,則提示大寫鎖定鍵打開。這種方法並不十分准確,網上有一些插件能判斷大寫鎖定,在這里只是簡單地做了一下判斷。

 提示文字( Chrome下 )

①獲得焦點、點擊時

②輸入時

     失去焦點時與此效果相同

    失去焦點時與此效果相同

     失去焦點時與此效果相同

                 失去焦點時與此效果相同

③失去焦點為空時

④出現大寫時

密碼欄目至此結束。

 

重復密碼:失去焦點時判斷是否和密碼一致

reister.html代碼片段:

<div class="ipt">
    <input type="password" name="rupwd" id="rupwd" value="" placeholder="確認密碼" />
    <span id="rupwdchk"></span>
</div>

register.js代碼片段:

 1 $("#rupwd").focus(function(){
 2     
 3                     var noticeMsg = '再次輸入你設置的密碼';
 4                     notice($("#rupwdchk"),noticeMsg);
 5             })
 6                .click(function(){
 7             
 8                     var noticeMsg = '再次輸入你設置的密碼';
 9                     notice($("#rupwdchk"),noticeMsg);
10             }).keydown(function(){
11             
12                     //把焦點移至郵箱欄目
13                     if(event.keyCode == 13){
14                         
15                         $("#yzm").focus();
16                     }
17             })
18                 .blur(function(){
19             
20                     if(this.value == $("#upwd").val() && this.value!=""){
21                     
22                         success($("#rupwdchk"),"");
23 
24                         rpwdval = true;
25                     }else if(this.value == ""){
26                     
27                         $("#rupwdchk").html("");
28                     }else{
29                     
30                         var errorMsg = '兩次輸入的密碼不一致';
31                         error($("#rupwdchk"),errorMsg);
32                     }
33 });

提示文字

①獲得焦點、點擊時

②失去焦點時和密碼不一致、一致時分別為

至此重復密碼結束。

 

驗證碼:不區分大小寫

驗證碼采用4位,可以包含的字符為數字1-9,字母a-f

點擊驗證碼和刷新按鈕都能刷新驗證碼

register.html驗證碼代碼部分:

1 <div class="ipt iptend">
2     <input type='text' id='yzm' name='yzm' placeholder="驗證碼">
3     <img id='yzmpic' src='' style="cursor:pointer"> <!-- 驗證碼圖片 -->
4     <a style="cursor:pointer" id='changea'>
5         <img id="refpic" src="images/ref.jpg" alt="驗證碼"> <!-- 驗證碼刷新按鈕圖片 -->
6     </a>
7     <span id='yzmchk'></span>
8     <input type='hidden' id='yzmHiddenNum' name='yzmHiddenNum' value=''> <!-- 隱藏域,內容是驗證碼輸出的數字,用戶輸入的字符與其進行對比 -->
9 </div>

register.js驗證碼部分:

  1 //驗證碼按鈕
  2 $("#refpic").hover(function(){
  3         
  4             $(this).attr("src","images/refhover.jpg");
  5         },function(){
  6         
  7             $(this).attr("src","images/ref.jpg");
  8         }).mousedown(function(){
  9         
 10             $(this).attr("src","images/refclick.jpg");
 11         }).mouseup(function(){
 12         
 13             $(this).attr("src","images/ref.jpg");
 14         });
 15         
 16         //生成驗證碼函數
 17         function showval() {
 18 
 19             num = '';
 20             for (i = 0; i < 4; i++) {
 21 
 22                 tmp = Math.ceil(Math.random() * 15);//Math.ceil上取整;Math.random取0-1之間的隨機數
 23                 if (tmp > 9) {
 24                     switch (tmp) {
 25                         case(10):
 26                             num += 'a';
 27                             break;
 28                         case(11):
 29                             num += 'b';
 30                             break;
 31                         case(12):
 32                             num += 'c';
 33                             break;
 34                         case(13):
 35                             num += 'd';
 36                             break;
 37                         case(14):
 38                             num += 'e';
 39                             break;
 40                         case(15):
 41                             num += 'f';
 42                             break;
 43                     }
 44                 } else {
 45                     num += tmp;
 46                 }
 47 
 48                 $('#yzmpic').attr("src","../valcode.php?num="+num);
 49             }
 50             $('#yzmHiddenNum').val(num);
 51         }
 52 
 53         //生成驗證碼以及刷新驗證碼
 54         showval();
 55         $('#yzmpic').click(function(){
 56         
 57             showval();
 58         });
 59         $('#changea').click(function(){
 60         
 61             showval();
 62         });
 63 
 64         //驗證碼檢驗
 65         function yzmchk(){
 66         
 67             if($("#yzm").val() == ""){
 68             
 69                 var errorMsg = '驗證碼不能為空';
 70                 error($("#yzmchk"),errorMsg);
 71             }else if($("#yzm").val().toLowerCase()!=$("#yzmHiddenNum").val()){
 72             
 73                 //不區分大小寫
 74                 var errorMsg = '請輸入正確的驗證碼';
 75                 error($("#yzmchk"),errorMsg);
 76             }else{
 77             
 78                 success($("#yzmchk"),"");
 79 
 80                 yzmval = true;
 81             }
 82         }
 83 
 84         //驗證碼的blur事件
 85         $("#yzm").focus(function(){
 86         
 87             var noticeMsg = '不區分大小寫';
 88             notice($("#yzmchk"),noticeMsg);
 89         }).click(function(){
 90         
 91             var noticeMsg = '不區分大小寫';
 92             notice($("yzmdchk"),noticeMsg);
 93         }).keydown(function(){
 94             
 95             //提交
 96             if(event.keyCode == 13){                
 97                 
 98                 //先檢驗后提交
 99                 yzmchk();
100                 formsub();
101             }
102         }).blur(function(){
103         
104             yzmchk();
105 });

valcode.php驗證碼生成php代碼:

 1 <?php 
 2 
 3     header("content-type:image/png");
 4     $num = $_GET['num'];
 5     $imagewidth = 150;
 6     $imageheight = 54;
 7     
 8     //創建圖像
 9     $numimage = imagecreate($imagewidth, $imageheight);
10     
11     //為圖像分配顏色
12     imagecolorallocate($numimage, 240,240,240); 
13 
14     //字體大小
15     $font_size = 33;
16     
17     //字體名稱
18     $fontname = 'arial.ttf';
19     
20     //循環生成圖片文字
21     for($i = 0;$i<strlen($num);$i++){
22         
23         //獲取文字左上角x坐標
24         $x = mt_rand(20,20) + $imagewidth*$i/5;
25         
26         //獲取文字左上角y坐標
27         $y = mt_rand(40, $imageheight);
28         
29         //為文字分配顏色
30         $color = imagecolorallocate($numimage, mt_rand(0,150),  mt_rand(0,150),  mt_rand(0,150));
31         
32         //寫入文字
33         imagettftext($numimage,$font_size,0,$x,$y,$color,$fontname,$num[$i]);
34     }
35     
36     //生成干擾碼
37     for($i = 0;$i<2200;$i++){
38         $randcolor = imagecolorallocate($numimage, rand(200,255), rand(200,255), rand(200,255));
39         imagesetpixel($numimage, rand()%180, rand()%90, $randcolor);
40     }
41     
42     //輸出圖片
43     imagepng($numimage);
44     imagedestroy($numimage);
45 ?>

注:把字體"Arial"放在服務器的相應目錄

提示文字

①獲得焦點時、點擊時

②為空且失去焦點時

③輸入錯誤、輸入正確且失去焦點時分別為

驗證碼至此結束。

 

使用協議:默認勾選;

register.html相應代碼:

<span class="fuwu">
        <input type="checkbox" name="agree" id="agree" checked="checked">
        <label for="agree">我同意  <a href="#">" 服務條款  "</a><a href="#">" 網絡游戲用戶隱私權保護和個人信息利用政策 "</a>
        </label>
</span>

register.js相應代碼:

 1 if($("#agree").prop("checked") == true){
 2     
 3         fuwuval = true;
 4     }
 5 
 6 $("#agree").click(function(){
 7     
 8         if($("#agree").prop("checked") == true){
 9 
10             fuwuval = true;
11             $("#sub").css("background","#69b3f2");
12         }else{
13         
14             $("#sub").css({"background":"#f2f2f2","cursor":"default"});
15         }    
16 });

效果圖

①勾選之后

②未勾選

 

提交按鈕:檢測是否所有欄目都填寫正確,否則所有填寫錯誤的欄目將給出錯誤提示。全部填寫正確后提交並且發送驗證郵件到注冊郵箱中,郵件的驗證地址在3日后失效

首先在register.js開始部分定義幾個參數:nameval,emailval,pwdval,rpwdval,yzmval,fuwuval,全部設為0;當相應欄目符合規定之后,把相應的參數設為true。當所有的參數都為true之后,提交至registerChk.php,否則return false。

register.html相應代碼:

<button type="button" id="sub">立即注冊</button>

register.js相應代碼:

參數設置:

var nameval,emailval,pwdval,rpwdval,yzmval,fuwuval = 0;

提交事件:

 1 function formsub(){
 2     
 3         if(nameval != true || emailval!=true || pwdval!=true || rpwdval!=true || yzmval!=true || fuwuval!=true){
 4         
 5             //當郵箱有下拉菜單時點擊提交按鈕時不會自動收回菜單,因為下面的return false,所以在return false之前判斷下拉菜單是否彈出
 6             if(nameval != true && $("#unamechk").val()!=""){
 7             
 8                 var errorMsg = '請輸入用戶名';
 9                 error($("#namechk"),errorMsg);
10             }
11 
12             if($(".autoul").show()){
13             
14                 $(".autoul").hide();
15             }
16 
17             //以下是不會自動獲得焦點的欄目如果為空時,點擊注冊按鈕給出錯誤提示
18             if($("#uemail").val() == ""){
19             
20                 var errorMsg = '郵箱不能為空';
21                 error($("#uemailchk"),errorMsg);        
22             }
23 
24             if($("#upwd").val() == ""){
25             
26                 var errorMsg = '密碼不能為空';
27                 error($("#upwdchk"),errorMsg);        
28             }
29 
30             if($("#rupwd").val() == ""){
31             
32                 var errorMsg = '請再次輸入你的密碼';
33                 error($("#rupwdchk"),errorMsg);        
34             }
35 
36             if($("#yzm").val() == ""){
37             
38                 var errorMsg = '驗證碼不能為空';
39                 error($("#yzmchk"),errorMsg);        
40             }
41 
42         }else{
43         
44             $("#register-form").submit();
45         }
46     }
47 
48     $("#sub").click(function(){
49         
50         formsub();
51 });

顯示效果

有欄目為空時點擊提交按鈕

 

注冊以及發送郵件

使用了Zend Framework( 1.11.11 )中的zend_email組件。Zend Framework的下載地址是:https://packages.zendframework.com/releases/ZendFramework-1.11.11/ZendFramework-1.11.11.zip。在Zend Framework根目錄下library路徑下,剪切Zend文件至服務器下,在注冊頁面中引入Zend/Mail/Transport/Smtp.php和Zend/Mail.php兩個文件。

當點擊提交按鈕時,表單將數據提交至register_chk.php,然后頁面在當前頁跳轉至register_back.html,通知用戶注冊結果並且進郵箱激活。

驗證郵箱的地址參數使用用戶名和一個隨機生成的key。

register_chk.php

 1 <?php 
 2 
 3     include_once 'conn/conn.php';
 4     include_once 'Zend/Mail/Transport/Smtp.php';
 5     include_once 'Zend/Mail.php';
 6     
 7     //激活key,生成的隨機數
 8     $key = md5(rand());
 9     
10     //先寫入數據庫,再發郵件
11     //寫入數據庫
12     //判斷是否開啟magic_quotes_gpc
13     if(get_magic_quotes_gpc()){
14     
15         $postuname = $_POST['uname'];
16         $postupwd = $_POST['upwd'];
17         $postuemail = $_POST['uemail'];
18     }else{
19         
20         $postuname = addslashes($_POST['uname']);
21         $postupwd = addslashes($_POST['upwd']);
22         $postuemail = addslashes($_POST['uemail']);
23     }
24 
25     function check_input($value){
26     
27         // 如果不是數字則加引號
28         if (!is_numeric($value)){
29         
30             $value = mysql_real_escape_string($value);
31         }
32         return $value;
33     }
34     
35     $postuname = check_input($postuname);
36     $postupwd = check_input($postupwd);
37     $postuemail = check_input($postuemail);
38 
39     $sql = "insert into user(uname,upwd,uemail,activekey)values('".trim($postuname)."','".md5(trim($postupwd))."','".trim($postuemail)."','".$key."')";
40 
41     $num = $conne->uidRst($sql);
42     if($num == 1){
43         
44         //插入成功時發送郵件
45         //用戶激活鏈接
46         $url = 'http://'.$_SERVER['HTTP_HOST'].'/php/myLogin/activation.php';
47         //urlencode函數轉換url中的中文編碼
48         //帶反斜杠
49         $url.= '?name='.urlencode(trim($postuname)).'&k='.$key;
50         //定義登錄使用的郵箱
51         $envelope = 'dee1566@126.com';
52         
53         //激活郵件的主題和正文
54         $subject = '激活您的帳號';
55         $mailbody = '注冊成功,<a href="'.$url.'" target="_blank">請點擊此處激活帳號</a>';
56         
57         //發送郵件
58         //SMTP驗證參數
59         $config = array(
60                 
61                 'auth'=>'login',
62                 'port' => 25,
63                 'username'=>'dee1566@126.com',
64                 'password'=>'你的密碼'
65                 );
66         
67         //實例化驗證的對象,使用gmail smtp服務器
68         $transport = new Zend_Mail_Transport_Smtp('smtp.126.com',$config);
69         $mail = new Zend_Mail('utf-8');
70         
71         $mail->addTo($_POST['uemail'],'獲取用戶注冊激活鏈接');
72         $mail->setFrom($envelope,'發件人');
73         $mail->setSubject($subject);
74         $mail->setBodyHtml($mailbody);
75         $mail->send($transport);
76 
77         echo "<script>self.location=\"templets/register_back.html\";</script>";
78 
79     }else{
80     
81         echo "<script>self.location=\"templets/register_back.html?error=1\";</script>";
82     }
83 ?>

 

郵箱中收取的郵件截圖:

然后點擊郵箱中的鏈接進行激活,把數據庫中的active設置為1。

activation.php

 1 <?php 
 2 session_start();
 3 header('Content-type:text/html;charset=utf-8');
 4 include_once 'conn/conn.php';
 5 
 6 $table = "user";
 7 
 8 if(!empty($_GET['name']) && !is_null($_GET['name'])){
 9                     
10     //urlencode會對字符串進行轉義。所以這里要進行處理
11     if(get_magic_quotes_gpc()){
12     
13         $getname = stripslashes(urldecode($_GET['name']));
14     }else{
15     
16         $getname = urldecode($_GET['name']);
17     }
18 
19     //urldecode反轉url中的中文編碼
20     $sql = "select * from ".$table." where uname='".$getname."' and activekey='".$_GET['k']."'";
21 
22     $num = $conne->getRowsNum($sql);
23     if($num>0){
24         
25         $rs = $conne->getRowsRst($sql);    
26 
27         //此時數據庫里的字符串是不會帶反斜杠的    
28         //因此要為下面的SQL語句加上反斜杠
29         $rsname = addslashes($rs['uname']);
30 
31         $upnum = $conne->uidRst("update ".$table." set active = 1 where uname = '".$rsname."' and activekey = '".$rs['activekey']."'");
32 
33         if($upnum>0){
34             
35             $_SESSION['name'] = urldecode($getname);
36             echo "<script>alert('您已成功激活');window.location.href='main.php';</script>";
37         }else{
38             
39             echo "<script>alert('您已經激活過了');window.location.href='main.php';</script>";
40         }
41     }else{
42         
43         echo "<script>alert('激活失敗');window.location.href='templets/register.html';</script>";
44     }
45 }
46 
47 ?>

關於注冊成功后的郵件頁和跳轉頁,這里不做了。 

關於數據庫防注入的幾種方式magic_quote_gpc,addslashes/stripslashes,mysql_real_eascpae_string,我做了一張表格

 

 

數據庫設計:

user表

1 create table user (id int primary key auto_increment,
2 uname varchar(14) not null default '',
3 upwd char(32) not null default '',
4 uemail varchar(50) not null default '',
5 active tinyint(4) default '0',
6 activekey char(32) not null defalut ''
)engine=innodb default charset=utf8

說明:md5的長度是32。

 

模塊的目錄結構如下:

ROOT:
├─conn
│ ├─conn.php

├─templets
│ ├─css
│ │ ├─common.css
│ │ ├─register.css
│ │
│ ├─images
│ │
│ └─js
│ ├─jquery-1.8.3.min.js
│ ├─register.js
│ ├─emailup.js

├─chkname.php
├─chkemail.php
├─valcode.php
├─register_chk.php
├─activation.php
├─arial.ttf

└─Zend

模塊至此結束。

 

作者: 小dee
說明:作者寫博目的是記錄開發過程,積累經驗,便於以后工作參考。
如需轉載,請在文章頁面保留此說明並且給出原文鏈接。謝謝!


免責聲明!

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



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