2015-02-24 70 views
1

試圖驗證micropost表單的標題和正文。我一直試圖弄清楚這一天。它越來越個人... :)Rails 4表單驗證正則表達式(標題,正文)

我是新來的兩個軌(1.5個月)和正則表達式(1天)

標題:我想允許UTF-8字符和空格 身體:我想允許使用UTF-8字符,空格和標點符號。

http://rubular.com/(紅寶石v 2.1.5)告訴我這將是OK:

​​

但當我嘗試這個辦法:

validates :title, presence: true, length: { minimum: 10, maximum: 60 }, format: { with: /[[:alpha:]]*[[:space:]]*/, message: "only letters" } 

它可以讓數字和字符這樣的+! %/ =(滑過。)

下面也失敗了。它不允許使用空格 - 至少在包含數字或其他奇怪字符時會引發錯誤:

format: { with: /\A[[:alpha:]]*[[:space:]]*\z/, message: "only letters" } 

我也試圖讓這樣的事情,但沒什麼區別,也失敗了:

REGEX = ........ 
format: { with: REGEX, message: "only letters" } 

這些失敗過:

format: { with: /\A[\p{L}\ ]\z/ 
format: { with: /[\p{L}\ ]/ 

提前感謝!

編輯 我的模型idea.rb

class Idea < ActiveRecord::Base 
belongs_to :user 
has_many :taggings, dependent: :destroy 
has_many :tags, through: :taggings 
attr_reader :tag_tokens 
acts_as_likeable 
has_many :likes, foreign_key: :likeable_id 
default_scope -> { order(created_at: :desc) } 
validates :user_id, presence: true 
validates :title, presence: true, length: { minimum: 10, maximum: 60 }, format: { with: /[[:alpha:]]|[[:space:]]/, message: 'only letters'} 
validates :intro, presence: true, length: { minimum: 60, maximum: 160 } 
validates :tag_ids, presence: true 
.... 
private 
def idea_params 
params.require(:idea).permit(:title, :intro, :content, :user_id, :name) 
end 
end 

這不允許在開頭的數字,但可以讓他們在其他地方:

validates :title, presence: true, length: { minimum: 10, maximum: 60 }, format: { with: /\A[[:alpha:]]|[[:space:]]\z/, message: 'only letters'} 

這不允許空間:

/\A([[:alpha:]]|[[:space:]]+)\z/ 

這允許空間但數量太多:

/([[:alpha:]]|[[:space:]]+)/ 

接受數字太:

/(\ p {L} +)/ /[\ p {L} \ S] +/

回答

0

的解決方案是:

/\A[\p{L}\s]+\z/ 

此接受任何Unicode(UTF-8)字母和任何數量的空間,但沒有數字或其他字符(例如:%/ =()+!)在一個單詞的任何地方或它自己。

最後... :)

0

我花了大約正則表達式爲UTF-8信息從Ruby language documentation site.

字符爲我工作

# /[[:alpha:]]|[[:space:]]/ 
class Selection 
    include Mongoid::Document 
    field :name, type: String 
    validates :name, presence: true, format: { with: /[[:alpha:]]|[[:space:]]/, message: 'only letters'} 
end 

但是當你使用存在選項意味着你不能只有空格。

可以測試與

+0

**感謝**此@farhatmihalko不幸的是有這個在我的潛行仍然不能正常工作:驗證:標題,存在:真,長度:{最低:10,最大:60},格式:{with:/ [[:alpha:]] | [[:space:]] /,message:'only letters'}但是你是否重新把你在我的模型中寫的所有上面的代碼?這會引發其他問題嗎?:我會如何處理我的原始線?你的代碼在模型中出現在哪裏?而且我在開發中使用了sqlite和postgredb - 那麼我將如何改變你的第二行呢? – Zsolt 2015-02-24 17:38:39

+0

@Zsolt你可以提供你的模型 – 2015-02-24 17:50:27

+0

當然@farhatmihalko編輯了原來的問題,增加了模型。 – Zsolt 2015-02-26 11:59:12