javascript 如何在javascript中验证数字和大写字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10186297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate number and capital letter in javascript
提问by greenthunder
I want to validate password :
我想验证密码:
- contain at least 1 number
- contain at least 1 capital letter (uppercase)
- contain at least 1 normal letter (lowercase)
- 包含至少 1 个数字
- 包含至少 1 个大写字母(大写)
- 包含至少 1 个普通字母(小写)
I used this code
我用了这个代码
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)
}
}
One thing that make me confuse is why if I input a number, it also count as uppercase letter???
让我困惑的一件事是为什么如果我输入一个数字,它也算作大写字母???
采纳答案by gabitzish
"1".toUpperCase == "1" ! What do you say about that :) You could do your checking like this:
"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++;
}
Now if b, c, or d equals 0, there is a problem.
现在如果 b、c 或 d 等于 0,则有问题。
回答by georg
Regular expressions are more suitable for this. Consider:
正则表达式更适合于此。考虑:
var containsDigits = /[0-9]/.test(password)
var containsUpper = /[A-Z]/.test(password)
var containsLower = /[a-z]/.test(password)
if (containsDigits && containsUpper && containsLower)
....ok
A more compact but less compatible option is to use a boolean aggregate over an array of regexes:
一个更紧凑但不太兼容的选项是在正则表达式数组上使用布尔聚合:
var rules = [/[0-9]/, /[A-Z]/, /[a-z]/]
var passwordOk = rules.every(function(r) { return r.test(password) });
回答by mjbnz
toUpperCase() and toLowerCase() will still return the character if it's not able to be converted, so your tests will succeed for numbers.
如果无法转换, toUpperCase() 和 toLowerCase() 仍将返回字符,因此您的数字测试将成功。
Instead, you should check first that isNaN(a[i])
is true before testing using toLowerCase/toUpperCase.
相反,isNaN(a[i])
在使用 toLowerCase/toUpperCase 进行测试之前,您应该首先检查是否为真。
回答by KooiInc
The very short way could be:
非常简短的方法可能是:
var pwd = document.getElementById("pass").value,
valid = Number(/\d/.test('1abcD'))+
Number(/[a-z]/.test('1abcD'))+
Number(/[A-Z]/.test('1abcD')) === 3;