How to check number and capital letter in javascript

I want to check the password:

  • contain at least 1 digits
  • contain at least 1 capital letter (uppercase)
  • contain at least 1 normal letter (lower case)

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 makes me embarrassed is why, if I entered a number, is it also considered an uppercase letter ???

+5
source share
4 answers

"1" .toUpperCase == "1"! What can you say about this :) You can make your choice as follows:

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 is 0, a problem arises.

+1
source

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

, :

var rules = [/[0-9]/, /[A-Z]/, /[a-z]/]
var passwordOk = rules.every(function(r) { return r.test(password) });

: test, every

+4

toUpperCase () and toLowerCase () will still return a character if it cannot be converted, so your tests will succeed for numbers.

Instead, you should first check what isNaN(a[i])is true before testing using toLowerCase / toUpperCase.

0
source

A very short path can be:

var pwd = document.getElementById("pass").value,
    valid = Number(/\d/.test('1abcD'))+
            Number(/[a-z]/.test('1abcD'))+
            Number(/[A-Z]/.test('1abcD')) === 3;
0
source

All Articles