Created
January 17, 2019 10:15
-
-
Save xijo/a88a8fab9d4d1fb934e1663515217242 to your computer and use it in GitHub Desktop.
Simple email validation micro gem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Gem::Specification.new do |s| | |
s.name = 'email_validator' | |
s.version = '0.1.0' | |
s.platform = Gem::Platform::RUBY | |
s.author = 'Betterplace Developers' | |
s.email = '[email protected]' | |
s.summary = 'Simple email validation for rails' | |
s.description = "Stay simple but don't interfere with `mail`" | |
s.files = ['email_validator.rb'] | |
s.require_path = '.' | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EmailValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
record.errors[attribute] << error_message unless valid?(value) | |
end | |
VALID_EMAIL_PATTERN = / | |
\A\.? | |
[a-z0-9\#$%&'*+\/=?^_`{|}~-]+ | |
(?:\.[a-z0-9\#$%&'*+\/=?^_`{|}~-]*)* | |
@ | |
(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+ | |
[a-z0-9] | |
(?:[a-z0-9-]*[a-z0-9])? | |
\z | |
/ix | |
def self.valid?(email) | |
VALID_EMAIL_PATTERN.match?(email) | |
end | |
def valid?(email) | |
VALID_EMAIL_PATTERN.match?(email) | |
end | |
private | |
def error_message | |
options[:message] || :invalid | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment