我正在开发一个需要根据以下条件验证密码的Rails 3应用程序:must be at least 6 characters and include one number and one letter.
这是我的正则表达式:
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."}
现在,如果我输入密码(例如:dogfood),它将通过。但我需要做的是通过上述标准。
我在正则表达式方面并不是那么出色,所以非常感谢任何帮助!
答案 0 :(得分:29)
使用前瞻断言:
/^(?=.*[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.
从技术上讲,在这种情况下你不需要锚,但使用它们是个好习惯。