2013-05-21 160 views
1

製作一個簡單的Ruby on Rails應用程序,作爲需要用戶註冊的練習。設計驗證不斷註冊失敗

一切工作順利,直到我實現了一個「PROFILE_NAME」字段

這裏是我的「用戶」的模式正則表達式驗證:

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

然而配置文件名「喬恩只是拒絕通過。這個錯誤從哪裏來,除了我的'用戶'模型?

回答

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

1

試試這個樣子,這是工作的罰款

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

我只是用「喬恩的測試中Rubular正則表達式。沒有匹配。

我沒有優化正則表達式編碼器。但下面的正則表達式仍然適用。

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

所以儘量

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