We help IT Professionals succeed at work.

Javascript Regular Expression for Mixed Case

Garbonzo_Horowitz
Garbonzo_Horowitz asked
on
Can someone offer advice on how to write a Javascript regular expression that requires mixed case?
That is: at least 1 lower case and at least 1 upper case letter.

I ran accross an article online saying it was impossible to do in Javascript so I was hoping for some help with this.
I'm validating a password form field and one of the requirements is that it must be mixed case.

I'm checking for a single number by:
if(/[0-9]/.test(temp))

and for a single letter by:
if(/[A-Za-z]/.test(temp))

but I'm not sure how to test for a lower case letter AND an upper case letter.


Comment
Watch Question

IT Guru
Most Valuable Expert 2011
Commented:
This requires at least one number, at least one lower case letter, and at least one upper case letter:

if(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/.test(temp))
Terry WoodsIT Guru
Most Valuable Expert 2011

Commented:
The syntax (?=.*blah) is a "positive lookahead" which looks ahead for "blah" after any other characters (.*)
Most Valuable Expert 2011
Top Expert 2015
Commented:
I go into detail about this in my article on lookaround, and I also give examples of the very restrictions you are seeking (and which Terry has so eloquently provided). If interested, see the section, "Passwords Containing Special Characters and of a Specific Length."

Author

Commented:
Excellent solutions. I'm going to have to split points for this one.

@Terry - When validating I'm giving the user a prompt for the error type. For example if they forgot to put in a letter or if they forgot to put in a number.  All I really need now is a check for mixed case so I think I can do without the first lookforward (?=.*\d) to ignore the digit lookup? Is that correct?  So your suggestion if(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/.test(temp))     would become       if(/^(?=.*[a-z])(?=.*[A-Z])/.test(temp))    if I only wanted to find upper and lower case letters, is that correct?

@kaufmed - That is the best explaination of RegEx lookaround I have come accross. Really nice article. Thanks.

Author

Commented:
Thank You.
Terry WoodsIT Guru
Most Valuable Expert 2011

Commented:
Yes, your pattern is correct for requiring at least one each of an upper and lower case letter. Note that a common addition to that type of pattern is a restriction on length - the following would limit the value to be between 6 and 15 characters:
if(/^(?=.*[a-z])(?=.*[A-Z]).{6,15}$/.test(temp))