2011-10-23 134 views
1

我正尝试在Ruby on Rails中创建用于正确用户名验证的正则表达式,但出于某种原因,我在做所有用户名输入无效的情况时出错。我允许使用大写字母,小写字母,数字和下划线。Ruby on Rails正则表达式无效

Ruby on Rails的名称验证的正则表达式代码:

validates :name, :format => {:with => /\A[A-Za-z\d_]\z/} 

我在做什么错?

感谢

+0

尝试使用资本\ Z或与尝试^和$,而不是 –

回答

1
# \A[A-Za-z\d_]\z 
# 
# Options:^and $ match at line breaks 
# 
# Assert position at the beginning of the string «\A» 
# Match a single character present in the list below «[A-Za-z\d_]» 
# A character in the range between “A” and “Z” «A-Z» 
# A character in the range between “a” and “z” «a-z» 
# A single digit 0..9 «\d» 
# The character “_” «_» 
# Assert position at the very end of the string «\z» 

这是你的表达。你真的想匹配一个字符吗?

笔者认为:

/^\w+$/ 

这是你在找什么。 \ w是您写的内容的简写字符类。上述正则表达式将

3
validates :name, :format => {:with => /^[A-Za-z0-9\_]+$/} 

尼斯页面匹配只由一串A-ZA-Z0-9_在红宝石测试正则表达式:http://rubular.com/

+0

我不认为应该验证一个空字符串。你做? – FailedDev

+0

ohh该死的权利,...固定 – davidb

+0

除... ...用'^ $'替换'\ A \ z' 请参阅:http://guides.rubyonrails.org/security.html#regular-expressions – nessur