1

What would be the best way to check that a javascript string is at least four characters long, contains at least one lowercase letter, one uppercase letter and a digit?

user1334130
  • 1,131
  • 3
  • 18
  • 25

3 Answers3

1

Testing for lowercase letters has already been covered elsewhere:

function hasLowerCase(str) {
    return (/[a-z]/.test(str));
}

It's trivial to modify that to implement hasUpperCase and hasDigits.

Once you have written these functions, you can just check that:

if( hasLowerCase(passwd) && hasUpperCase(passwd) && hasDigits(passwd) ) {
    // Its a valid password!
}

If you use it in many places, consider making a new function:

function isPasswordValid(str) {
    return hasLowerCase(passwd) && hasUpperCase(passwd) && hasDigits(passwd);
}

Which you can further use like:

if( isPasswordValid("passwd") ) {
    // ...
}
Community
  • 1
  • 1
jsalonen
  • 29,593
  • 15
  • 91
  • 109
1

Here's a quick validation function:

function validate(str) {
    return str.length > 3 && /[a-z]/.test(str) && /[A-Z]/.test(str) && /[0-9]/.test(str) ;
}

It checks the length and then runs regular expressions looking for lowercase, uppercase and numbers (in that order). If all are true (length > 3 and has lowercase and has uppercase and has a number) it returns true. Otherwise, it returns false.

use it like this:

validate("aaaa")  // returns false
validate("aA1")   // returns false
validate("aA12")  // returns true
ColBeseder
  • 3,579
  • 3
  • 28
  • 45
0

I wrote a function, same like ColBeseder .added a type checking string

function check( str ){

    return ( typeof str == 'string') &&
           ( str.length >= 4 ) &&
           /[a-z]/.test( str ) &&
           /[A-Z]/.test( str ) && 
           /[0-9]/.test( str )

}

and call its as check('AAA1a') , which returns a boolean

rab
  • 4,134
  • 1
  • 29
  • 42