【问题标题】:Rails - REGEX - validating length of non whitespace / special charactersRails - REGEX - 验证非空格/特殊字符的长度
【发布时间】:2019-06-22 21:28:35
【问题描述】:

我有一些带有长度验证的字段,可以通过输入 n 个空格来绕过。我正在尝试编写一种方法,仅验证字母数字字符的数量(不是空格或特殊字符)。

我已经做到了以下几点:

 validates :title,
            presence: true,
            length: { minimum: 4, maximum: 140 },
            format: { with: /([A-z0-9])/ }

我无法得到的是如何验证与格式匹配的标题长度。例如,我想允许标题为“野兽”,但在字符数中只计算“野兽”。这将允许“野兽”并在长度验证中包含空格

rails 中是否有内置的东西可以让我这样做?或者如果不是,编写自定义方法的最佳方法是什么?

提前致谢

【问题讨论】:

    标签: ruby-on-rails regex validation activerecord


    【解决方案1】:

    为了扩展@NeverBe 的答案,我选择了:

    class AlphanumericLengthValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        minimum_length = options.fetch(:length, 100)
        stripped_value = value ? value.gsub(/[^0-9a-zA-Z]/, '') : nil
        message = "must be at least #{minimum_length} alphanumeric characters in length"
        return if stripped_value&.length && stripped_value.length >= minimum_length
        record.errors.add(attribute, message) if !stripped_value || stripped_value.length < minimum_length
      end
    end
    

    这让我可以这样做:

      validates :title, alphanumeric_length: { length: 8 }
    

    【讨论】:

      【解决方案2】:

      如果你有像“filtered_title”这样的辅助列,你可以这样做:

      before_save :filter_title
      
      def filter_title
        self.filtered_title = title.gsub(/[^0-9a-zA-Z]/, '') // strip unneeded chars
      end
      

      和你的验证器,但在新列上

       validates :filtered_title,
                  presence: true,
                  length: { minimum: 4, maximum: 140 },
                  format: { with: /([A-z0-9])/ }
      

      【讨论】:

        猜你喜欢
        • 2011-09-06
        • 1970-01-01
        • 2023-01-17
        • 2013-05-16
        • 2022-10-13
        • 2012-05-14
        • 2021-09-28
        • 1970-01-01
        • 2011-03-09
        相关资源
        最近更新 更多