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!
?= 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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With