AS3的密碼強度驗證函式
- public static function evaluatePwd(sPW:String):int
- {
- if (sPW.length <= 4)
- return 0;
- var Modes:int = 0;
- for (var i:int = 0; i < sPW.length; i++)
- {
- Modes |= CharMode(sPW.charCodeAt(i));
- }
-
- return bitTotal(Modes);
-
- function CharMode(iN:int):int
- {
- if (iN>=48 && iN <=57)
- return 1;
- if (iN>=65 && iN <=90)
- return 2;
- if (iN>=97 && iN <=122)
- return 4;
- else
- return 8;
- }
-
- function bitTotal(num:int):*
- {
- var modes:int = 0;
- for (var i:int = 0; i < 4; i++)
- {
- if (num & 1) modes ++;
- num >>>= 1;
- }
- return modes;
- }
- }
public static function evaluatePwd(sPW:String):int{if (sPW.length <= 4)return 0;var Modes:int = 0;for (var i:int = 0; i < sPW.length; i++){Modes |= CharMode(sPW.charCodeAt(i));}return bitTotal(Modes);function CharMode(iN:int):int{if (iN>=48 && iN <=57)return 1;if (iN>=65 && iN <=90)return 2;if (iN>=97 && iN <=122)return 4;elsereturn 8;}function bitTotal(num:int):*{var modes:int = 0;for (var i:int = 0; i < 4; i++){if (num & 1) modes ++;num >>>= 1;}return modes;}}
另外還有一個十分簡單的演算法
- public static function evaluatePwd2(sPW:String):int
- {
- return sPW.replace(/^(?:([a-z])|([A-Z])|([0-9])|(.)){5,}|(.)+$/g, "$1$2$3$4$5").length;
- }
public static function evaluatePwd2(sPW:String):int{return sPW.replace(/^(?:([a-z])|([A-Z])|([0-9])|(.)){5,}|(.)+$/g, "$1$2$3$4$5").length;}
我們可以用多種圖形化的介面甚至動畫去展現密碼的強度,舉個簡單的例子,例如我希望使用者在輸入密碼後1秒內沒有任何輸入動作,則驗證密碼的強度,並且已進度條的形式展示
首先註冊一個監聽
- pwdInputView.password.addEventListener(KeyboardEvent.KEY_UP, onKey);
pwdInputView.password.addEventListener(KeyboardEvent.KEY_UP, onKey);
然後看看監聽函數
- private var oldText:String;
-
- private function onKey(e:KeyboardEvent):void
- {
- if (oldText != pwdInputView.password.text && pwdInputView.password.text.length > 5)
- {
- oldText = pwdInputView.password.text;
- TweenLite.killTweensOf(updateStrengthView, false);
- TweenLite.delayedCall(1, updateStrengthView);
- }
- }
private var oldText:String;private function onKey(e:KeyboardEvent):void{if (oldText != pwdInputView.password.text && pwdInputView.password.text.length > 5){oldText = pwdInputView.password.text;TweenLite.killTweensOf(updateStrengthView, false);TweenLite.delayedCall(1, updateStrengthView);}}
首先定義一個oldText成員,用於記錄上次輸入的密碼,如果當前密碼和上次密碼不相同並且長度大於5,開始執行操作。我這裡用了TweenLite作為計時器,1秒後將執行強度判斷,如果發現使用者在1秒內再次有輸入操作,則銷毀當前TweenLite。
再看看如何用視圖來展示密碼強度,這裡不多作解釋了,只是一個簡單的動畫效果。
- private function updateStrengthView():void
- {
- var toWidth:Number = pwdInputView.strengthCanvas.width * CheckStrong.evaluatePwd(pwdInputView.password.text) * .25;
- TweenLite.to(pwdInputView.maskCanvas, 1.5, {width:toWidth, ease:Bounce.easeOut, overwrite:false});
- }
private function updateStrengthView():void{var toWidth:Number = pwdInputView.strengthCanvas.width * CheckStrong.evaluatePwd(pwdInputView.password.text) * .25;TweenLite.to(pwdInputView.maskCanvas, 1.5, {width:toWidth, ease:Bounce.easeOut, overwrite:false});}