2017-04-26 117 views
0

我想驗證我的應用程序中文本區域的字數。 我試過以下this SO question,但我不能讓我的工作。Rails 5客戶端驗證字數不起作用

我的驗證:

validates :skills_response, :length => { 
    :minimum => 5, 
    :maximum => 10, 
    :tokenizer => lambda { |str| str.scan(/\s+|$/) }, 
    :too_short => "must have at least %{count} words", 
    :too_long => "must have at most %{count} words" 
} 

我現在用的是client side validations gem,正如你所看到的,上面是不工作的,因爲它仍然是字符計數。

enter image description here

我也曾嘗試:tokenizer => lambda { |str| str.split }這也不能工作。爲什麼這會發生?

回答

2

長度統計字符而不是單詞。如果您要檢查的話,你可以將自己的自定義驗證器添加到模型:

validate :check_for_words 

def check_for_words 
     if self.skills_response.split.size > 10 
     errors.add(:base, "You must have less than 10 words") 
     end 
end 
0

你可以使用分裂和計數得到單詞的數量,然後創建一個函數返回true,並基於該假。

2.3.3 :001 > string = "Hello World today" 
=> "Hello World today" 
2.3.3 :002 > split = string.split(' ') 
=> ["Hello", "World", "today"] 
2.3.3 :003 > split.count 
=> 3 




validate :validation 

def validation 
    errors.add(:for_validation, "error") if form_field.split(' ').count < 10 
end