2013-03-20 44 views
0

我有一個用戶表,其中有一個名爲screen_name的行是一個字符串。Rails字段驗證不能按預期工作

在其他限制中,屏幕名稱不應包含像。 ,&%@等 爲此我構建了以下驗證:

validates :screen_name, presence: true, 
      length: { maximum: 15 }, 
      uniqueness: { case_sensitive: false }, 
      format: { with: /\w+/ } 

當我再輸入一個網名喜歡foo.bar有人欣然接受,並存儲在數據庫中。

我在做什麼錯?

# == Schema Information 
# 
# Table name: users 
# 
# id    :integer   not null, primary key 
# name   :string(255) 
# email   :string(255) 
# created_at  :datetime   not null 
# updated_at  :datetime   not null 
# password_digest :string(255) 
# remember_token :string(255) 
# admin   :boolean   default(FALSE) 
# screen_name  :string(255)  
# 

回答

1

改變你的驗證這樣/^\w*$/

您可以驗證這樣

validates_format_of :screen_name, :with => /^[A-Za-z0-9.&]*\z/ 
+0

感謝拉吉,即工作。你能告訴我/ \ w + /和/^\ w * $/ 之間的區別是什麼,因爲當我在Rubular.com中測試它們時,我看不到任何區別。 – MPL 2013-03-20 13:40:27

+1

@MPL嗨,接受我的回答,通過點擊綠色的寫符號 – 2013-03-20 13:42:04