【问题标题】:How to validate a character is not included in a string in Rails 5?如何验证 Rails 5 中的字符串中不包含字符?
【发布时间】:2019-08-25 16:01:19
【问题描述】:

我需要将 Regex 作为文本保存在我的数据库中,用户应该能够从 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

【问题讨论】:

    标签: ruby-on-rails regex ruby validation


    【解决方案1】:

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

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

    同一问题的答案here 解释了为什么我们选择这样的正则表达式:D

    【讨论】:

    • 那行不通。 (我在现在已删除的答案中犯了同样的错误。)那是因为"abc/def" == "abc\/def" #=&gt; true。用户输入需要逐键读取。
    【解决方案2】:

    试试这个:

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

    使带有/ 前面没有\ 的字符串无效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多