2017-04-26 1 views
0

내 응용 프로그램에서 텍스트 영역의 단어 수를 확인하려고합니다. 나는 다음과 같은 시도를했다 this SO question하지만 일할 수 없어요.레일즈 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

당신은 다음 사실 그 기반으로 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 
관련 문제