From 2a2b0a90dcdd3f782d476ff1ad067488ccfd4a42 Mon Sep 17 00:00:00 2001 From: Sebastian Kippe Date: Thu, 3 Dec 2020 14:49:37 +0100 Subject: [PATCH] Validate email address properly --- app/models/concerns/email_validatable.rb | 15 +++++++++++++++ app/models/user.rb | 5 ++++- 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 app/models/concerns/email_validatable.rb diff --git a/app/models/concerns/email_validatable.rb b/app/models/concerns/email_validatable.rb new file mode 100644 index 0000000..6a83881 --- /dev/null +++ b/app/models/concerns/email_validatable.rb @@ -0,0 +1,15 @@ +require 'mail' + +module EmailValidatable + extend ActiveSupport::Concern + + class EmailValidator < ActiveModel::EachValidator + def validate_each(record, attribute, value) + begin + a = Mail::Address.new(value) + rescue Mail::Field::ParseError + record.errors[attribute] << (options[:message] || "is not a valid address") + end + end + end +end diff --git a/app/models/user.rb b/app/models/user.rb index b2f3693..6987a0a 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,10 +1,13 @@ class User < ApplicationRecord + include EmailValidatable + # Relations has_many :invitations, dependent: :destroy validates_uniqueness_of :cn - validates_uniqueness_of :email validates_length_of :cn, :minimum => 3 + validates_uniqueness_of :email + validates :email, email: true # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable