demarches-normaliennes/app/models/champs/date_champ.rb
Martin d8220395c8 amelioration(usagers.dossiers.erreurs): ETQ usager, lorsque je soumets un dossier avec des erreurs, le format des erreurs est au format du DSFR
Update app/components/dossiers/errors_full_messages.rb
Update app/components/dossiers/errors_full_messages/errors_full_messages.html.haml

Co-authored-by: Colin Darie <colin@darie.eu>
2023-09-28 17:50:47 +02:00

46 lines
1 KiB
Ruby
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class Champs::DateChamp < Champ
before_validation :convert_to_iso8601, unless: -> { validation_context == :prefill }
validate :iso_8601
def search_terms
# Text search is pretty useless for dates so were not including these champs
end
def to_s
value.present? ? I18n.l(Time.zone.parse(value), format: '%d %B %Y') : ""
rescue ArgumentError
value.presence || "" # old dossiers can have not parseable dates
end
alias for_tag to_s
private
def convert_to_iso8601
return if likely_iso8601_format? && parsable_iso8601?
self.value = if /^\d{2}\/\d{2}\/\d{4}$/.match?(value)
Date.parse(value).iso8601
else
nil
end
end
def iso_8601
return if parsable_iso8601? || value.blank?
# i18n-tasks-use t('errors.messages.not_a_date')
errors.add :date, :not_a_date
end
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