验证标准:
密码必须包含 数字、字母(不区分大小写)和特殊字符,长度为8-16位!
function checkPwd(pwd)
if #pwd == 0 then
print("密码不能为空")
return false
end
if #pwd < 8 or #pwd > 16 then
print("密码长度为8-16位")
return false
end
local numberCnt, letterCnt, specialCnt, otherCnt = 0, 0, 0, 0
for s in string.gmatch(pwd, ".") do
-- print(s)
local ASCIICode = string.byte(s)
if ASCIICode >= 48 and ASCIICode <= 57 then
numberCnt = numberCnt + 1
elseif (ASCIICode >= 65 and ASCIICode <= 90) or
(ASCIICode >= 97 and ASCIICode <= 122) then
letterCnt = letterCnt + 1
elseif (ASCIICode >= 33 and ASCIICode <= 47) or
(ASCIICode >= 58 and ASCIICode <= 64) or
ASCIICode == 91 or
(ASCIICode >= 93 and ASCIICode <= 96) or
(ASCIICode >= 123 and ASCIICode <= 126) then
-- 转义字符(\ 92)要从特殊字符中剔除
specialCnt = specialCnt + 1
else
otherCnt = otherCnt + 1
end
end
if otherCnt > 0 then
print("密码含有非法字符")
return false
elseif numberCnt == 0 then
print("密码必须包含数字")
return false
elseif letterCnt == 0 then
print("密码必须包含字母")
return false
elseif specialCnt == 0 then
print("密码必须包含特殊字符")
return false
end
print("密码格式正确")
return true
end
local pwdStr = ""
checkPwd(pwdStr) -- 密码不能为空
pwdStr = "abc"
checkPwd(pwdStr) -- 密码长度为8-16位
pwdStr = "12345678901234567"
checkPwd(pwdStr) -- 密码长度为8-16位
pwdStr = "12345678中文"
checkPwd(pwdStr) -- 密码含有非法字符
pwdStr = "1234\ndabcd"
checkPwd(pwdStr) -- 密码含有非法字符
pwdStr = "abcdefgh"
checkPwd(pwdStr) -- 密码必须包含数字
pwdStr = "12345678"
checkPwd(pwdStr) -- 密码必须包含字母
pwdStr = "1234abcd"
checkPwd(pwdStr) -- 密码必须包含特殊字符
pwdStr = "1234abcd!@#"
checkPwd(pwdStr) -- 密码格式正确
ps
关于特殊字符的支持可以参考:
在 Linux 系统上的密码中支持的特殊字符:
波浪线 ~
at符号 @
散列标记 #
下划线 _
插入标记 ^
星号 *
百分号 %
斜杠 /
句点 .
加号 +
冒号 :
分号 ;
等号 =
在 Windows 系统上的密码中支持的特殊字符:
波浪线 ~
at符号 @
下划线 _
斜杠 /
加号 +
冒号 :