gre*_*der 5 javascript validation
我想验证密码:
我用过这段代码
function validate()
{
var a=document.getElementById("pass").value
var b=0
var c=0
var d=0;
for(i=0;i<a.length;i++)
{
if(a[i]==a[i].toUpperCase())
b++;
if(a[i]==a[i].toLowerCase())
c++;
if(!isNaN(a[i]))
d++;
}
if(a=="")
{
alert("Password must be filled")
}
else if(a)
{
alert("Total capital letter "+b)
alert("Total normal letter "+c)
alert("Total number"+d)
}
}
Run Code Online (Sandbox Code Playgroud)
让我困惑的一件事是,如果我输入一个数字,它也算作大写字母???
正则表达式更适合于此。考虑:
var containsDigits = /[0-9]/.test(password)
var containsUpper = /[A-Z]/.test(password)
var containsLower = /[a-z]/.test(password)
if (containsDigits && containsUpper && containsLower)
....ok
Run Code Online (Sandbox Code Playgroud)
更为紧凑但兼容性较差的选项是在正则表达式数组上使用布尔聚合:
var rules = [/[0-9]/, /[A-Z]/, /[a-z]/]
var passwordOk = rules.every(function(r) { return r.test(password) });
Run Code Online (Sandbox Code Playgroud)
"1".toUpperCase == "1" !你对此有何看法:)你可以像这样进行检查:
for(i=0;i<a.length;i++)
{
if('A' <= a[i] && a[i] <= 'Z') // check if you have an uppercase
b++;
if('a' <= a[i] && a[i] <= 'z') // check if you have a lowercase
c++;
if('0' <= a[i] && a[i] <= '9') // check if you have a numeric
d++;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果 b、c 或 d 等于 0,则存在问题。
| 归档时间: |
|
| 查看次数: |
12710 次 |
| 最近记录: |