Skip to content

Commit 9ae037e

Browse files
committed
Merge pull request #1 from VentureSpirit/allow-subdomains
Added subdomain validator
2 parents 1299f7b + 6ecff5d commit 9ae037e

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class Person
2525
include ActiveModel::Validations
2626
attr_accessor :name, :email
2727

28-
validates :email, email_domain_inclusion: {allowed_domains: ["hotmail.com", "gmail.com"]}
28+
validates :email, email_domain_inclusion: {allow_subdomains: true, allowed_domains: ["hotmail.com", "gmail.com"]}
2929
end
3030
```
3131

lib/email_domain_inclusion.rb

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,29 @@
55
# +allowed_domains+ can be an array of strings, or a Proc that returns an array of strings
66
class EmailDomainInclusionValidator < ActiveModel::EachValidator
77
def validate_each(record, attribute, value)
8-
domains = options[:allowed_domains]
9-
domains = domains.call if domains.respond_to?(:call)
10-
domain = domain_from_email(value)
11-
unless domains.include?(domain)
8+
allow_subdomains = options[:allow_subdomains]
9+
unless valid_full_domain?(value) || (allow_subdomains && valid_subdomain?(value))
1210
record.errors[attribute] << options[:message] || "domain_not_in_list"
1311
end
1412
end
1513

1614
private
15+
def valid_subdomain?(value)
16+
domain = domain_from_email(value)
17+
allowed_domains.any? { |allowed_domain| domain.end_with? ".#{allowed_domain}" }
18+
end
19+
20+
def valid_full_domain?(value)
21+
domain = domain_from_email(value)
22+
allowed_domains.include?(domain)
23+
end
24+
25+
def allowed_domains
26+
domains = options[:allowed_domains]
27+
domains = domains.call if domains.respond_to?(:call)
28+
domains
29+
end
30+
1731
def domain_from_email(email)
1832
Mail::Address.new(email).try(:domain).try(:downcase)
1933
rescue Mail::Field::ParseError

0 commit comments

Comments
 (0)