代码之家  ›  专栏  ›  技术社区  ›  Alvaro Alday

如何验证rails 5中的字符串中没有包含字符?

  •  0
  • Alvaro Alday  · 技术社区  · 7 年前

    我要救一个 正则表达式 作为数据库中的文本,用户应该能够从ui修改它,我需要验证用户不会输入 无转义正斜杠(/) 形式上。

    我没有发现任何关于排除字符或 这甚至是可能的。

    到目前为止,我的课看起来是这样的:

    class Setings < Trigger
      REGEX = /this is/
    
      # Validations
      # -----------------------------
    
      validates :rest_period,   numericality: { only_integer: true, greater_than: 0 }, if: :rest_period?
      validates :custom_regex,  presence: true, format: { with: REGEX, allow_blank: true, message: "must be a valid Regex" },
    end
    

    我需要验证这一点,因为用户可以输入一个字符,该字符可能会破坏其他软件类中稍后的函数。

    我对这个功能做了一些rspec测试

    describe Settings do
      context "when invalid" do
        subject { Settings.new }
    
        context "when completion_page] is not a valid regex" do
          before          { subject.completion_page = "^Applicant Information.*" } # This should be valid
          it("has error") { expect(subject.errors.full_messages).not_to include "Must be a valid Regex" }
        end
    
        context "when completion_page] includes unescaped forward slashes" do
          before          { subject.completion_page = "/^Applicant Information.*/" } # This should be invalid
          before          { is_expected.to be_invalid }
          it("has error") { expect(subject.errors.full_messages).to include "Must be a valid Regex" }
        end
      end
    end
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   ttuan    7 年前

    您应该尝试使用此正则表达式来匹配不包含无转义正斜杠的字符串:

    REGEX = /\A((?!\/).)*\z/
    

    同一问题的答案 here 解释为什么我们选择这样的regex:d

        2
  •  0
  •   Broquel    7 年前

    试试这个:

    REGEX = /\A((?![^\\]\/).)*\z/
    

    使字符串无效 / 前面没有 \ .

    推荐文章