【发布时间】: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