我正在开发一个需要根据以下标准验证密码的 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),它将通过。但我需要它做的是通过上述标准。
我不太擅长正则表达式,因此非常感谢任何和所有帮助!
最佳答案
使用前瞻断言:
/^(?=.*[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.
从技术上讲,在这种情况下,您不需要 anchor ,但使用它们是一个好习惯。
关于regex - 使用正则表达式验证密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11992544/