18

I am working on a Rails 3 application that needs to validate the password based on the following criteria: must be at least 6 characters and include one number and one letter.

Here is my Regex:

validates :password, :format => {:with => /^[([a-z]|[A-Z])0-9_-]{6,40}$/, message: "must be at least 6 characters and include one number and one letter."}

Right now if I put in a password of (for ex: dogfood) it will pass. But what I need it to do is to pass the criteria above.

I am not all that great at regex, so any and all help is greatly appreciated!

dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189

1 Answers1

35

Use lookahead assertions:

/^(?=.*[a-zA-Z])(?=.*[0-9]).{6,}$/
  |             |          |
  |             |          |
  |             |          Ensure there are at least 6 characters.
  |             |
  |             Look ahead for an arbitrary string followed by a number.
  |                        
  Look ahead for an arbitrary string followed by a letter.

Technically in this case you don't need the anchors, but it's good habit to use them.

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
  • wow, that works perfectly! thanks so much! Can you explain a little bit about lookahead assertions? – dennismonsewicz Aug 16 '12 at 17:41
  • 3
    Lookaheads look forward for a pattern, here it will look from start for anything (.) 0 or more times followed by [a-zA-Z] and same with [0-9]. Lookaheads doesnt go forward so you'll still be at position 0 when it comes to .{0,6} which will verify the length of 6+ – netdigger Aug 16 '12 at 17:42
  • See edited answer for explanation. But @DavidEverlöf thank you for appending a more in-depth explanation. – Andrew Cheong Aug 16 '12 at 17:44
  • 10
    Yup Lookahead assertions are best for password regexes. +1 for that. Check this RegEx out: `^.*(?=.{10,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$`. This one checks least number of chars, atleast 1 digit, atleast 1 lowercase alphabet, atleast 1 uppercase alphabet, atleast 1 special char in the set given. It is very configurable and easier to change what you want (well relatively). This gives a good insight: [Regular-Expressions.info](http://www.regular-expressions.info/lookaround.html) – Kash Aug 16 '12 at 17:53
  • Thanks for all of the help! One day I too will conquer the world of Regex lol – dennismonsewicz Aug 16 '12 at 17:59
  • @Kash, looks good but you'll lose the maximum length check that way. – Yvo Jul 20 '15 at 08:27
  • 8
    Use \A and \z for anchors. Current version of Rails doesn't accept ^ and $ as anchors without `multiline: true` . Apparently it's a security risk: [link](http://stackoverflow.com/a/17760113) – Atte Juvonen Feb 06 '16 at 14:48