1

制作一个简单的 Ruby on Rails 应用程序作为练习,需要用户注册。

一切正常,直到我在“profile_name”字段上实施正则表达式验证

这是我的“用户”模型:

validates :profile_name, presence: true,
                           uniqueness: true,
                           format: {
                            with: /^a-zA-Z0-9_-$/,
                            message: 'Must be formatted correctly.'
                           }   

然而,个人资料名称“jon”只是拒绝通过。除了我的“用户”模型之外,这个错误可能来自哪里?

4

3 回答 3

1

您需要在范围周围添加括号,以便正则表达式匹配“任何范围”而不是“按顺序排列的所有范围”。在末尾加上一个 + 以允许它多次匹配范围内的任何内容。您还需要将行的开头和结尾更改为字符串的开头和结尾!

validates :profile_name, presence: true,
                         uniqueness: true,
                         format: {
                           with: /\A[a-zA-Z0-9_-]+\z/,
                           message: 'Must be formatted correctly.'
                         }

细节:

\A # Beginning of a string (not a line!)
\z # End of a string
[...] # match anything within the brackets
+ # match the preceding element one or more times

生成和检查正则表达式的真正有用的资源:http ://www.myezapp.com/apps/dev/regexp/show.ws

于 2013-05-21T09:26:59.220 回答
1

像这样尝试,它工作正常

 validates :name, presence: true,
                               uniqueness: true,
                               format: {
                                with: /\A[a-zA-Z0-9_-$]+\z/,
                                message: 'Must be formatted correctly.'
                               } 
于 2013-05-21T09:22:37.697 回答
1

我刚刚用“jon”在Rubular中测试了你的正则表达式。没有匹配。

我不是优化的正则表达式编码器。但是下面的正则表达式仍然有效。

/^[a-zA-Z0-9_-]+$/

所以试试

 validates :name, presence: true,
                           uniqueness: true,
                           format: {
                            with: /^[a-zA-Z0-9_-]+$/,
                            message: 'Must be formatted correctly.'
                           } 
于 2013-05-21T09:24:15.933 回答