简体   繁体   English

正则表达式+ Ruby On Rails

[英]Regular expression + Ruby On Rails

I would like to validate my users, so they can only use az and - in their username. 我想验证我的用户,因此他们只能在用户名中使用az和-

validates_format_of :username, :with => /[a-z]/

However this rule also allows _ - and capital letters. 然而,这条规则也允许_ -和大写字母。 How do I only allow letters, numbers, _ and - ? 如何只允许使用字母,数字, _-

This regex makes sure that the first character is a lowercase letter and the rest are either lowercase letters, numbers, hyphens or underscores. 此正则表达式确保第一个字符是小写字母,其余字符是小写字母,数字,连字符或下划线。

/\A[a-z][a-z0-9_-]+\Z/

If you don't care about the first character, you can use 如果您不关心第一个字符,则可以使用

/\A[a-z0-9_-]+\Z/

If you want to make sure the name is minimum 4 characters long: 如果要确保名称长度至少为4个字符,请执行以下操作:

/\A[a-z][a-z0-9_-]{3,}\Z/

If you want to make sure the length is between 4 and 8 如果要确保长度在4到8之间

/\A[a-z][a-z0-9_-]{3,7}\Z/

If the length should be 6 如果长度应为6

/\A[a-z][a-z0-9_-]{5}\Z/

Your regular expression is not specific enough. 您的正则表达式不够具体。 You're looking for something like: 您正在寻找类似的东西:

:with => /\A[a-z_]+\Z/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM