【问题标题】:Rails 5 client-side validation of word count not workingRails 5客户端验证字数不起作用
【发布时间】:2017-04-26 23:11:39
【问题描述】:

我正在尝试验证我的应用程序中文本区域的字数。 我已经尝试关注this SO question,但我无法让我的工作。

我的验证:

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,如您所见,上述方法不起作用,因为它仍在计算字符数。

我也尝试过:tokenizer => lambda { |str| str.split },但也没有用。为什么会这样?

【问题讨论】:

    标签: ruby-on-rails ruby validation client-side-validation


    【解决方案1】:

    长度计算字符而不是单词。如果要检查单词,可以将自己的自定义验证器添加到模型中:

    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
    

    【讨论】:

      【解决方案2】:

      您可以使用 split 和 count 来获取单词的数量,然后创建一个函数来根据它返回 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
      

      【讨论】:

        猜你喜欢
        • 2017-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-26
        • 2013-01-09
        相关资源
        最近更新 更多