Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

827 : emails validation in person #965

Merged
merged 2 commits into from
May 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/models/person.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Person < ApplicationRecord
accepts_nested_attributes_for :location

validate :preferred_contact_method_present!
validates_with EmailValidator, fields: [:email, :email_2]

def name_and_email
"#{name} (#{email})"
Expand Down
13 changes: 13 additions & 0 deletions app/validators/email_validator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class EmailValidator < ActiveModel::Validator
REGEX_EMAIL = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
def validate(record)
options[:fields].each { |field| validate_email(record, field) } if options[:fields].any?
end

private

def validate_email(record, field)
value = record.send(field)
record.errors.add field, (options[:message] || "is not valid") if !value.nil? && !value.strip.empty? && !REGEX_EMAIL.match?(value)
end
end
39 changes: 39 additions & 0 deletions spec/validators/email_validator_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
require 'rails_helper'

RSpec.describe EmailValidator do
describe 'Email validation' do
let(:validator) { EmailValidator.new({fields: fields}) }
let(:fields) { [:email] }
let(:errors) { double('ActiveModel::Errors') }

context 'when only one mail is set' do
it 'should validate valid address' do
person = double('model', errors: errors, email: 'valid_email@test.org')
expect(errors).not_to receive(:add)
validator.validate(person)
end

it 'should find an error when the address is invalid' do
person = double('model', errors: errors, email: 'invalid@missingtld')
expect(errors).to receive(:add).with(:email, "is not valid")
validator.validate(person)
end
end

context 'when the two mails are set' do
let(:fields) { [:email, :email_2] }

it 'should find an error in email and email_2' do
person = double('model', errors: errors, email: 'invalid@missingtld', email_2: 'invalid_2@missingtld')
expect(errors).to receive(:add).twice
validator.validate(person)
end

it 'should find an error only in email' do
person = double('model', errors: errors, email: 'invalid@missingtld', email_2: 'valid@test.org')
expect(errors).to receive(:add).once
validator.validate(person)
end
end
end
end