在Ruby(服务器端)中,验证电子邮件地址的最佳/简易方法是什么?
在Ruby(服务器端)中,验证电子邮件地址的最佳/简易方法是什么?
您可以查看它是否与此Rails验证器中使用的正则表达式匹配:
validates_format_of :email,:with => /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
但如果您使用Devise,只需执行以下操作:
validates_format_of :email,:with => Devise::email_regexp
来源: http://lindsaar.net/2008/4/14/tip-4-detecting-a-valid-email-address
编辑1:
用于测试的有用网站: http://www.rubular.com/
在Ruby中?与任何语言一样。
向该地址发送确认电子邮件,并附带一个链接,接收方必须在被视为完全验证之前点击该链接。
即使地址格式完全正确(如加粗文本所示),也可能有许多原因导致其无效(该地址没有实际用户、被垃圾邮件过滤器阻止等)。唯一确定的方法是完成某种类型的端到端交易。
validates :email, presence: true, format: /\w+@\w+\.{1}[a-zA-Z]{2,}/
检查电子邮件字段不为空,并且在“@”之前和之后有一个或多个字符
更具体地说,是在@
之前有任意一个或多个单词字符,在@
之后和之间有至少一个.
后跟至少2个字母的任意一个或多个单词字符
.+@.+\.{1}.{2,}
。 - zarathustravalidates :my_email_attribute, :email => true
在模型之外进行验证
EmailValidator.valid?('narf@example.com') # boolean
希望这能帮助大家。快捷表单:
validates :email, :format => /@/
正规表达式中的普通形式:
validates :email, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/ }
Source: Validator Class
您可以使用
<%=email_field_tag 'to[]','' ,:placeholder=>"Type an email address",:pattern=>"^([\w+-.%]+@[\w-.]+\.[A-Za-z]{2,4},*[\W]*)+$",:multiple => true%>
由于主要答案的博客网站崩溃了,因此在这里通过nice cacher 或 gist 提供了代码片段:
# http://my.rails-royce.org/2010/07/21/email-validation-in-ruby-on-rails-without-regexp/
class EmailValidator < ActiveModel::EachValidator
# Domain must be present and have two or more parts.
def validate_each(record, attribute, value)
address = Mail::Address.new value
record.errors[attribute] << (options[:message] || 'is invalid') unless (address.address == value && address.domain && address.__send__(:tree).domain.dot_atom_text.elements.size > 1 rescue false)
end
end
该代码用于验证电子邮件格式是否正确。其中,":email"是需要验证的属性名称,"/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i"是用于验证电子邮件格式的正则表达式。正则表达式的具体含义可以参考上述链接。
validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
validates_format_of :email,:with => Devise::email_regexp
config.email_regexp = /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
# lib/email_validator.rb
class EmailValidator < ActiveModel::EachValidator
EmailAddress = begin
qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'
dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'
atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-' +
'\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'
quoted_pair = '\\x5c[\\x00-\\x7f]'
domain_literal = "\\x5b(?:#{dtext}|#{quoted_pair})*\\x5d"
quoted_string = "\\x22(?:#{qtext}|#{quoted_pair})*\\x22"
domain_ref = atom
sub_domain = "(?:#{domain_ref}|#{domain_literal})"
word = "(?:#{atom}|#{quoted_string})"
domain = "#{sub_domain}(?:\\x2e#{sub_domain})*"
local_part = "#{word}(?:\\x2e#{word})*"
addr_spec = "#{local_part}\\x40#{domain}"
pattern = /\A#{addr_spec}\z/
end
def validate_each(record, attribute, value)
unless value =~ EmailAddress
record.errors[attribute] << (options[:message] || "is not valid")
end
end
end
validates :email , :email => true
validates :email, :presence => true,
:length => {:minimum => 3, :maximum => 254},
:uniqueness => true,
:email => true