在 Rails 验证中计算单词 [英] Counting words in a rails validation
问题描述
我正在使用以下验证来计算 rails 中的单词数(我从 Rails 文档中得到了示例),但这并不准确:
I'm using the following validation to count words in rails (I got the example from the Rails docs), but it's not real accurate:
validates :body, :length => {
:minimum => 50,
:maximum => 300,
:tokenizer => lambda { |str| str.scan(/\w+/) },
:too_short => "must have at least %{count} words",
:too_long => "must have at most %{count} words"
}
一位用户试图发布 291 个字的内容(这是 Word 给出的计数),但由于太长而被拒绝.我不知道所使用的表达方式到底有什么问题,也不知道什么是确保准确字数的好的表达方式.
A user tried to post something that's 291 words (that's the count Word gives) and it was rejected as too long. I don't know exactly what's wrong with the expression that's being used, or what might be a good expression to ensure an accurate word count.
推荐答案
你应该扫描/\s+|$/而不是扫描/\w+/并将最大值减一,因为 \w 单词字符匹配可以意外的异常字符,因为只有 A-Za-z0-9_- 有效.
Instead of scanning for /\w+/ you should scan for /\s+|$/ and decrease the max by one since the \w word character match can be unexpected with unusual characters since only A-Za-z0-9_- are valid.
这篇关于在 Rails 验证中计算单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!