0

I need to save a Regex as text in my database, the users should be able to modify it from the UI, I need to validate the users won't input a unescaped forward slash (/) in the form.

I Haven't found anything about excluding characters or if this is even possible.

So far, my class looks something like this:

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

I need to validate this since the user could input a character that could break a later function in some other software class.

I have some RSpec tests for this functionality

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
Alvaro Alday
  • 343
  • 3
  • 19

2 Answers2

0

You should try this regex to match string which doesn't contain unescaped forward slash:

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

The answer for a same question here explains why we choose regex like that :D

ttuan
  • 114
  • 4
  • That won't work. (I made the same mistake in my now-deleted answer.) That's because `"abc/def" == "abc\/def" #=> true`. User input needs to be read key-by-key. – Cary Swoveland Apr 04 '19 at 03:06
0

Try this:

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

Invalidates strings with / not preceded by \.

Broquel
  • 64
  • 9