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?

3
  • 4
    Sharing some code would be the best way, I guess... Commented Apr 18, 2013 at 11:14
  • Regular expressions, I guess.. Commented Apr 18, 2013 at 11:15
  • What methods have you tried already? What problems did you face? Commented Apr 18, 2013 at 11:16

3 Answers 3

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") ) { // ... } 
Sign up to request clarification or add additional context in comments.

5 Comments

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?
Yes you can do exactly that!
OK so I'll need a check for all three.
Testing for all three in one regex is not a good idea because you don't know what order they're in.
Wow stop! I definitely meant using THREE regexes just for this exactly same reason! Sorry for ambiguity!
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 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.