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?
Asked
Active
Viewed 130 times
1
-
4Sharing some code would be the best way, I guess... – Hiren Pandya Apr 18 '13 at 11:14
-
Regular expressions, I guess.. – Shadow The GPT Wizard Apr 18 '13 at 11:15
-
What methods have you tried already? What problems did you face? – Lix Apr 18 '13 at 11:16
3 Answers
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") ) {
// ...
}
-
I already looked at regular expressions and that example but am not too familiar with regex. Would it possible to have one regex statement or would I need three statements - one for the lower, upper and digit cases, then check that all three are true? – user1334130 Apr 18 '13 at 11:19
-
-
-
Testing for all three in one regex is not a good idea because you don't know what order they're in. – ColBeseder Apr 18 '13 at 11:27
-
Wow stop! I definitely meant using THREE regexes just for this exactly same reason! Sorry for ambiguity! – jsalonen Apr 18 '13 at 11:29
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