JS实现校验密码强度

JavaScript012

JS实现校验密码强度,第1张

/*

*@description 校验密码强度的方法

*@param {String} val 待校验强度的密码

*@return {Number} 密码强度等级,数字越大强度越高

*/

function checkPwd(val){

    var res = 2

    // 长度不低于6位和12位,强度分别+1和+2

    res += val.length >= 6 ? 1 : 0

    res += val.length >= 12 ? 2 : 0

    // 包含小写字母,强度+1或+2

    res += /[a-z]/.test(val) ? (val.length <8 || /\d{4}/.test(val) ? 1 : 2) : 0

    // 包含大写字母,强度+1或+2

    res += /[A-Z]/.test(val) ? (val.length <8 || /\d{4}/.test(val) ? 1 : 2) : 0

    // 包含特殊字符,强度+1或+2

    res += /[^a-zA-Z\s\d]/.test(val) ? (val.length <8 || /\d{4}/.test(val) ? 1 : 2) : 0

    return Math.floor(res / 2)

}

<script>

function$(id){returndocument.getElementById(id)}

functiontrim(s){returns.replace(/(^\s*)|(\s*$)/g,"")}

functionLogin(){

varuser=$("user").value

varpwd=$("pwd").value

if(!trim(user)){alert("用户名不能为空")$("user").focus()returnfalse}

if(!trim(pwd)){alert("密码不能为空")$("pwd").focus()returnfalse}

if(pwd.length<6){alert("密码不能少于6位数")$("pwd").focus()returnfalse}

if(pwd.length>16){alert("密码不能大于16位数")$("pwd").focus()returnfalse}

$("loginform").submit()

}

</script>

<formname="loginform"id="loginform">

<inputtype="text"name="user"id="user"/>

<inputtype="password"name="pwd"id="pwd"/>

<inputtype="button"value="提交"onclick="Login()"/>

</form>

扩展资料

判断密码强度是否有数字:

///</summary>

///<paramname="str">密码字符串</param>

functionJugePwdNumeric(sNum)

{

//三、数字:

//0分:没有数字

//10分:1个数字

//20分:大于等于3个数字

varcount=0

for(vari=0i<=sNum.length-1i++)

{

//数字的KEYCODE96-105

if((sNum.charCodeAt(i)>=96)&&(sNum.charCodeAt(0)<=105))

{

count+=1

}

}

if(count==0)

{

pwdLevel+=0

}

else

{

hasNumeric=true

if(count<3)

{

pwdLevel+=10

}

else

{

pwdLevel+=20

}

}

}