tags:

views:

116

answers:

4

I have the following password requirements:

1) Should be 6-15 characters in length
2) Should have atleast one lowercase character
3) Should have atleast one uppercase character
4) Should have atleast one number
5) Should have atleast one special character
6) Should not have spaces

Can anyone suggest me a RegEx for this requirement?

+9  A: 

Not sure I would use a Regex for that : regex are not always the right tool for any possible kind of job...

Here, you specified a list of 6 requirements ; so, why not just use 6 different tests, one per requirement ?
Those 6 different tests, should I add, would be really simple -- while a Regex would be much harder to write (you asked for help -- you would probably not have for the 6 tests).

This would make your code a lot more easier to understand, I'd bet ;-)
And also : easier to maintain ; and easier to add/remove/change one of the condition corresponding to one of the requirements.

Pascal MARTIN
Reg ex would be useful to use for both client and server validation.
thekaido
The second advantage of this method would be providing better error messages when a password does not meet the requirements. For instance, indicating *which* required character type was omitted. There's nothing more frustrating than entering a password you think will work and getting a generic error message.
Emily
@thekaido : same for the 6 tests, even if the syntax might be a bit different ;;; @Emily : so true !
Pascal MARTIN
@Pascal, Wait wait! One tool doesn't work for all jobs? If that's so you're also saying I shouldn't be using a chainsaw for the fine decorative woodworking I'm about to do! Phew! I got lucky there!
Jason D
+3  A: 

Regexlib.com has tons of examples for you and a searchable database of reg ex's.

thekaido
+1 for the link
citronas
+4  A: 

I'm not entirely sure what you mean by "special character" so I am interpreting this to mean \W, but you can change this if you want:

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*\W)\S{6,15}$
Mark Byers
+1, but beware the bug: http://blog.stevenlevithan.com/archives/regex-lookahead-bug
Alan Moore
+1 Alan. It's always good to know about documented bugs!
Jason D
A: 
1 => /^.{6,15}$/
2 => /[a-z]/
3 => /[A-Z]/
4 => /\d/
5 => /[#{special_chars_for_regex}]/
6 => /^\S*$/
Justice
`\W` means *not-word-character*, not *not-whitespace* (that's `\S`, but you might as well incorporate that into the first condition like @Mark Byers did). Also, "special characters" just means punctuation.
Alan Moore
I changed `\W` to `\S` (thanks). I didn't feel like spelling out the full set of special chars, but `~!@#$%^:'",<.>/?()` might do in a pinch.
Justice