Merge pull request #8504 from mfo/US/fix-date-champs
correct(champs::date): renforce la validation d'un champs de type date
This commit is contained in:
commit
938e524060
2 changed files with 18 additions and 4 deletions
|
@ -39,7 +39,7 @@ class Champs::DateChamp < Champ
|
|||
private
|
||||
|
||||
def convert_to_iso8601
|
||||
return if valid_iso8601?
|
||||
return if likely_iso8601_format? && parsable_iso8601?
|
||||
|
||||
self.value = if /^\d{2}\/\d{2}\/\d{4}$/.match?(value)
|
||||
Date.parse(value).iso8601
|
||||
|
@ -49,12 +49,20 @@ class Champs::DateChamp < Champ
|
|||
end
|
||||
|
||||
def iso_8601
|
||||
return if valid_iso8601? || value.blank?
|
||||
return if parsable_iso8601? || value.blank?
|
||||
# i18n-tasks-use t('errors.messages.not_a_date')
|
||||
errors.add :date, errors.generate_message(:value, :not_a_date)
|
||||
end
|
||||
|
||||
def valid_iso8601?
|
||||
def likely_iso8601_format?
|
||||
/^\d{4}-\d{2}-\d{2}$/.match?(value)
|
||||
end
|
||||
|
||||
def parsable_iso8601?
|
||||
Date.parse(value)
|
||||
true
|
||||
rescue ArgumentError, # case 2023-27-02, out of range
|
||||
TypeError # nil
|
||||
false
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
describe Champs::DateChamp do
|
||||
let(:date_champ) { build(:champ_date) }
|
||||
let(:date_champ) { create(:champ_date) }
|
||||
|
||||
describe '#convert_to_iso8601' do
|
||||
it 'preserves nil' do
|
||||
|
@ -37,6 +37,12 @@ describe Champs::DateChamp do
|
|||
champ.save
|
||||
expect(champ.reload.value).to eq("2023-12-21")
|
||||
end
|
||||
|
||||
it 'converts to nil if false iso' do
|
||||
champ = champ_with_value("2023-27-02")
|
||||
champ.save
|
||||
expect(champ.reload.value).to eq(nil)
|
||||
end
|
||||
end
|
||||
|
||||
def champ_with_value(number)
|
||||
|
|
Loading…
Reference in a new issue