I want to validate password :
- contain at least 1 number
- contain at least 1 capital letter (uppercase)
- contain at least 1 normal letter (lowercase)
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???
I want to validate password :
- contain at least 1 number
- contain at least 1 capital letter (uppercase)
- contain at least 1 normal letter (lowercase)
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???
Share Improve this question edited Apr 17, 2012 at 6:42 Octavian Helm 39.6k19 gold badges99 silver badges102 bronze badges asked Apr 17, 2012 at 6:34 greenthundergreenthunder 7279 gold badges19 silver badges34 bronze badges4 Answers
Reset to default 9Regular 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 pact but less patible 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) });
Docs: test, every
"1".toUpperCase == "1" ! What do you say about that :) You could do your checking like this:
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.
toUpperCase() and toLowerCase() will still return the character if it's not able to be converted, so your tests will succeed for numbers.
Instead, you should check first that isNaN(a[i])
is true before testing using toLowerCase/toUpperCase.
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;