Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating Password using Regex

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!

like image 351
dennismonsewicz Avatar asked Aug 16 '12 17:08

dennismonsewicz


People also ask

What does ?= Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

Which of the following is the correct way if we want password to be validated with alphanumeric characters?

To validate the said format we use the regular expression ^[A-Za-z]\w{7,15}$, where \w matches any word character (alphanumeric) including the underscore (equivalent to [A-Za-z0-9_]). Next the match() method of string object is used to match the said regular expression against the input value.


1 Answers

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.

like image 148
slackwing Avatar answered Oct 11 '22 09:10

slackwing