2017-04-26 4 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とfalseを返す関数を作成します。

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 
関連する問題