使用正则表达式验证密码 [英] Validating Password using Regex

查看:50
本文介绍了使用正则表达式验证密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要根据以下标准验证密码的 Rails 3 应用程序:必须至少包含 6 个字符,并包含一个数字和一个字母.

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.

这是我的正则表达式:

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)它就会通过.但我需要它做的是通过上面的标准.

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!

推荐答案

使用先行断言:

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

这篇关于使用正则表达式验证密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆