Skip to content

Instantly share code, notes, and snippets.

@xijo
Created January 17, 2019 10:15
Show Gist options
  • Save xijo/a88a8fab9d4d1fb934e1663515217242 to your computer and use it in GitHub Desktop.
Save xijo/a88a8fab9d4d1fb934e1663515217242 to your computer and use it in GitHub Desktop.
Simple email validation micro gem
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 = 'developers@betterplace.org'
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
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