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 に答える