Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate number and capital letter in javascript

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???

like image 470
greenthunder Avatar asked Apr 17 '12 06:04

greenthunder


1 Answers

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) });

Docs: test, every

like image 132
georg Avatar answered Sep 28 '22 08:09

georg