简体   繁体   中英

Regular expression + Ruby On Rails

I would like to validate my users, so they can only use az and - in their username.

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:

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

If you want to make sure the length is between 4 and 8

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

If the length should be 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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