amelioration(Champs::EngagementJuridiqueChamp): valide le format

This commit is contained in:
Martin 2023-10-20 17:34:59 +02:00
parent d2657d83ac
commit 0428853f4d
3 changed files with 51 additions and 2 deletions

View file

@ -1,2 +1,7 @@
class Champs::EngagementJuridiqueChamp < Champ
# cf: https://communaute.chorus-pro.gouv.fr/documentation/creer-un-engagement/#1522314752186-a34f3662-0644b5d1-16c22add-8ea097de-3a0a
validates_with ExpressionReguliereValidator,
expression_reguliere: /([A-Z]|[0-9]|\-|\_|\+|\/)+/,
expression_reguliere_error_message: "Le numéro d'EJ ne peut contenir que des caractères alphanumérique et les caractères spéciaux suivant : “-“ ; “_“ ; “+“ ; “/“",
if: -> { validation_context != :brouillon }
end

View file

@ -2,9 +2,12 @@ class ExpressionReguliereValidator < ActiveModel::Validator
TIMEOUT = 1.second.freeze
def validate(record)
expression_reguliere = options[:expression_reguliere] || record.expression_reguliere
expression_reguliere_error_message = options[:expression_reguliere_error_message] || record.expression_reguliere_error_message
if record.value.present?
if !record.value.match?(Regexp.new(record.expression_reguliere, timeout: TIMEOUT))
record.errors.add(:value, :invalid_regexp, expression_reguliere_error_message: record.expression_reguliere_error_message)
if !record.value.match?(Regexp.new(expression_reguliere, timeout: TIMEOUT))
record.errors.add(:value, :invalid_regexp, expression_reguliere_error_message: expression_reguliere_error_message)
end
end
rescue Regexp::TimeoutError

View file

@ -0,0 +1,41 @@
describe Champs::EngagementJuridiqueChamp do
describe 'validation' do
let(:champ) { build(:champ_engagement_juridique, value: value) }
subject { champ.valid? }
context 'with [A-Z]' do
let(:value) { "ABC" }
it { is_expected.to be_truthy }
end
context 'with [0-9]' do
let(:value) { "ABC" }
it { is_expected.to be_truthy }
end
context 'with -' do
let(:value) { "-" }
it { is_expected.to be_truthy }
end
context 'with _' do
let(:value) { "_" }
it { is_expected.to be_truthy }
end
context 'with +' do
let(:value) { "+" }
it { is_expected.to be_truthy }
end
context 'with /' do
let(:value) { "/" }
it { is_expected.to be_truthy }
end
context 'with *' do
let(:value) { "*" }
it { is_expected.to be_falsey }
end
end
end