18

我正在开发一个需要根据以下标准验证密码的 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),它将通过。但我需要它做的是通过上述标准。

我不太擅长正则表达式,因此非常感谢任何和所有帮助!

4

1 回答 1

34

使用前瞻断言:

/^(?=.*[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.

从技术上讲,在这种情况下,您不需要锚点,但使用它们是一个好习惯。

于 2012-08-16T17:37:57.903 回答