From c2461f230c0b47e9635e34bb915de95c3851a4e4 Mon Sep 17 00:00:00 2001 From: krichtof Date: Tue, 11 Apr 2023 15:33:20 +0200 Subject: [PATCH] validate value for email champ --- app/models/champs/email_champ.rb | 7 +++++++ config/locales/en.yml | 4 ++++ config/locales/fr.yml | 4 ++++ spec/models/champs/email_champ_spec.rb | 29 ++++++++++++++++++++++++++ 4 files changed, 44 insertions(+) create mode 100644 spec/models/champs/email_champ_spec.rb diff --git a/app/models/champs/email_champ.rb b/app/models/champs/email_champ.rb index 0c17ea122..666fb9fc6 100644 --- a/app/models/champs/email_champ.rb +++ b/app/models/champs/email_champ.rb @@ -21,4 +21,11 @@ # type_de_champ_id :integer # class Champs::EmailChamp < Champs::TextChamp + validates :value, + format: { + with: Devise.email_regexp, + message: I18n.t('invalid', scope: 'activerecord.errors.models.email_champ.attributes.value') + }, + allow_nil: true, + if: -> { validation_context != :brouillon } end diff --git a/config/locales/en.yml b/config/locales/en.yml index 0f57fb79c..c0cac60ae 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -561,6 +561,10 @@ en: attributes: email: taken: ': Invitation already sent' + email_champ: + attributes: + value: + invalid: "is invalid. Fill in a valid email address, example: john.doe@example.fr" user: attributes: &error_attributes diff --git a/config/locales/fr.yml b/config/locales/fr.yml index 84c7b1dc1..e34848cfd 100644 --- a/config/locales/fr.yml +++ b/config/locales/fr.yml @@ -562,6 +562,10 @@ fr: attributes: email: taken: ': Invitation déjà envoyée' + email_champ: + attributes: + value: + invalid: "est invalide. Saisir une adresse éléctronique valide, exemple : john.doe@exemple.fr" user: attributes: &error_attributes reset_password_token: diff --git a/spec/models/champs/email_champ_spec.rb b/spec/models/champs/email_champ_spec.rb new file mode 100644 index 000000000..7addc1e55 --- /dev/null +++ b/spec/models/champs/email_champ_spec.rb @@ -0,0 +1,29 @@ +describe Champs::EmailChamp do + subject { build(:champ_email, value: value).tap(&:valid?) } + + describe '#valid?' do + context 'when the value is an email' do + let(:value) { 'jean@dupont.fr' } + + it { is_expected.to be_valid } + end + + context 'when the value is not an email' do + let(:value) { 'jean@' } + + it { is_expected.to_not be_valid } + end + + context 'when the value is blank' do + let(:value) { '' } + + it { is_expected.to_not be_valid } + end + + context 'when the value is nil' do + let(:value) { nil } + + it { is_expected.to be_valid } + end + end +end