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?
- 4Sharing some code would be the best way, I guess...Hiren Pandya– Hiren Pandya2013-04-18 11:14:53 +00:00Commented Apr 18, 2013 at 11:14
- Regular expressions, I guess..user447356– user4473562013-04-18 11:15:17 +00:00Commented Apr 18, 2013 at 11:15
- What methods have you tried already? What problems did you face?Lix– Lix2013-04-18 11:16:09 +00:00Commented Apr 18, 2013 at 11:16
3 Answers
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") ) { // ... } 5 Comments
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