tags:

views:

54

answers:

1

Hi,

I need a regex for a password which meets following constraints in my rails project:

  • have a minimum of 8 and a maximum of 16 characters
  • be alphanumeric only
  • contain at least one letter and one number.

My current regex is:

/^(?=.*\d)(?=.*([a-z]|[A-Z])).{8,16}$/

This allows me all the restrictions but the special characters part is not working. What is it that I am doing wrong. Can someone please correct this regex?

Thanks in advance.

+2  A: 
/^(?=.*\d)(?=.*[a-zA-Z])[0-9a-zA-Z]{8,16}$/

The last part of your regex, .{8,16}, allows any character with a dot.

The lookahead only makes sure that there's at least one digit and one letter - it doesn't say anything about other characters. Also, note that I've updated your letter matching part - you don't need two character classes.

Disallowing special characters in a password is totally counter intuitive. Why are you doing that?

Amarghosh
awesome. That works. Thanks
Priyank
The only times i've ever seen "alphanumeric only" password requirements, they were because some idiot couldn't be bothered to learn how to sanitize/escape data. Not that the OP is necessarily that idiot -- i'm going to bet he knows a few, though.
cHao
Well, if it was up to me, I'd let user type all the junk in the world for his password. However sometimes; uniformity with legacy site is more important to business than security. Go figure! :)
Priyank
Note, better to use `\A` and `\Z` instead of `^` and `$`. This string matches that regex: `"!\n1234abcd\n#"`
glenn jackman
I'd use `[[:alpha:]]` instead of `[a-zA-Z]` and `[[:digit:][:alpha:]]` instead of `[0-9a-zA-Z]`. More descriptive and should allow non-english chars
glenn jackman
glenn, quit complicating things. :) The regex is fine; if they're going to complain over a freaking **space**, for gawd's sake, what do you think they're going to do with 'ä'?
cHao