Improve organizations's slug validator (#20265)
This commit is contained in:
parent
74cc4ac39e
commit
479a09f77b
3 changed files with 24 additions and 1 deletions
|
|
@ -2,6 +2,7 @@
|
|||
# Validates if the give attribute is used across the reserved spaces.
|
||||
class CrossModelSlugValidator < ActiveModel::EachValidator
|
||||
FORMAT_REGEX = /\A[0-9a-z\-_]+\z/
|
||||
ORGANIZATION_FORMAT_REGEX = /\A(?![0-9]+\z)[0-9a-z\-_]+\z/
|
||||
|
||||
def validate_each(record, attribute, value)
|
||||
return if value.blank?
|
||||
|
|
@ -20,7 +21,8 @@ class CrossModelSlugValidator < ActiveModel::EachValidator
|
|||
end
|
||||
|
||||
def correct_format?(record, attribute, value)
|
||||
return false if value.match?(FORMAT_REGEX)
|
||||
format_regex = record.is_a?(Organization) ? ORGANIZATION_FORMAT_REGEX : FORMAT_REGEX
|
||||
return false if value.match?(format_regex)
|
||||
|
||||
record.errors.add(attribute, I18n.t("validators.cross_model_slug_validator.is_invalid"))
|
||||
end
|
||||
|
|
|
|||
|
|
@ -52,6 +52,11 @@ RSpec.describe Organization do
|
|||
it { is_expected.to allow_value("#abc").for(:text_color_hex) }
|
||||
it { is_expected.not_to allow_value("3.0").for(:company_size) }
|
||||
it { is_expected.to allow_value("3").for(:company_size) }
|
||||
|
||||
it { is_expected.to allow_value("1345abc").for(:slug) }
|
||||
it { is_expected.to allow_value("just_non_digit_characters").for(:slug) }
|
||||
it { is_expected.to allow_value("123_4").for(:slug) }
|
||||
it { is_expected.not_to allow_value("1234").for(:slug) }
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
|||
|
|
@ -80,4 +80,20 @@ RSpec.describe CrossModelSlugValidator do
|
|||
|
||||
it { is_expected.to be_valid }
|
||||
end
|
||||
|
||||
context "when organization's slug consists of only digits" do
|
||||
let(:organization) { build(:organization, slug: "1337") }
|
||||
|
||||
it "is invalid" do
|
||||
expect(organization).not_to be_valid
|
||||
end
|
||||
end
|
||||
|
||||
context "when organization's slug contains at least one non-digit character" do
|
||||
let(:organization) { build(:organization, slug: "1234a") }
|
||||
|
||||
it "is valid" do
|
||||
expect(organization).to be_valid
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue