在 Ruby 中验证电子邮件地址的最佳/简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4776907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:10:41  来源:igfitidea点击:

What is the best/easy way to validate an email address in Ruby?

ruby-on-railsrubyruby-on-rails-3

提问by Ran

What is the best/easy way to validate an email address in ruby (on the server side)?

在 ruby​​ 中验证电子邮件地址的最佳/简单方法是什么(在服务器端)?

回答by apneadiving

You could look whether or not it matches a regexp like the one used in this Rails validator:

您可以查看它是否与此 Rails 验证器中使用的正则表达式匹配:

validates_format_of :email,:with => /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/

But if you use Devise, simply do:

但是,如果您使用 Devise,只需执行以下操作:

validates_format_of :email,:with => Devise::email_regexp

Source: http://lindsaar.net/2008/4/14/tip-4-detecting-a-valid-email-address

来源:http: //lindsaar.net/2008/4/14/tip-4-detecting-a-valid-email-address

Edit 1:

编辑1:

useful website for tests: http://www.rubular.com/

有用的测试网站:http: //www.rubular.com/

回答by paxdiablo

In Ruby? The same way as in any language.

在红宝石?与任何语言的方式相同。

Send a confirmation email to the address with a link that the recipient has to click before the email address is considered fully validated.

向该地址发送一封确认电子邮件,其中包含收件人必须在电子邮件地址完全验证之前单击的链接。

There are any number of reasons why a perfectly formattedaddress may still be invalid (no actual user at that address, blocked by spam filters, and so on). The only way to know for sure is a successfully completed end-to-end transaction of some description.

格式完美地址可能仍然无效的原因有很多(该地址没有实际用户,被垃圾邮件过滤器阻止,等等)。唯一确定的方法是成功完成某种描述的端到端事务。

回答by partydog

validates :email, presence: true, format: /\w+@\w+\.{1}[a-zA-Z]{2,}/

checks that email field is not blank and that one or more characters are both preceding the '@' and following it

检查电子邮件字段是否不为空,并且在“@”之前和之后都有一个或多个字符

Added specificity, any 1 or more word characters before an the @and any 1 or more word character after and in between specifically 1 .and at least 2 letters after

增加了特殊性,the 之前的@任何 1 个或多个单词字符以及之后和之间的任何 1 个或多个单词字符,特别是.在后面的1 个和至少 2 个字母之间

回答by MZaragoza

I know that this is a old question but I was looking for a simple to way to do this. I came across a email_validator gemthis is really simple to set up and use.

我知道这是一个老问题,但我一直在寻找一种简单的方法来做到这一点。我遇到了一个email_validator gem,它的设置和使用非常简单。

as a validator

作为验证者

validates :my_email_attribute, :email => true

validates :my_email_attribute, :email => true

Validation outside a model

模型外验证

EmailValidator.valid?('[email protected]') # boolean

EmailValidator.valid?('[email protected]') # boolean

I hope that this help everyone.

我希望这对大家有帮助。

Happy Codding

快乐编码

回答by akshay

You can use

您可以使用

<%=email_field_tag 'to[]','' ,:placeholder=>"Type an email address",:pattern=>"^([\w+-.%]+@[\w-.]+\.[A-Za-z]{2,4},*[\W]*)+$",:multiple => true%>

回答by Kanmaniselvan

You can take reference from https://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_format_of

您可以参考https://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_format_of

validates_format_of :email, with: /\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

回答by Yurii Verbytskyi

If you are using Rails/Devise - addition to @apneadiving`s answer -

如果您使用的是 Rails/Devise - 除了@apneadiving 的答案 -

validates_format_of :email,:with => Devise::email_regexp

Devise::email_regexp is taken from config/initializers/devise.rb

Devise::email_regexp 取自 config/initializers/devise.rb

config.email_regexp = /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/

回答by Omer Aslam

Shortcut Form:

快捷方式:

 validates :email, :format => /@/

Normal Form (Regex) :

范式(正则表达式):

validates :email, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/ }

Source: Validator Class

来源:验证器类

回答by toobulkeh

Since the main answer's blog site was down, here is the snippet of code from that site via nice cacheror gist:

由于主要答案的博客站点已关闭,以下是通过nice cachergist来自该站点的代码片段:

# 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

回答by andrea

Send a confirmation mail , and I will usualy use this validator ... D.R.Y.

发送确认邮件,我通常会使用这个验证器......干

# 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

in your model

在你的模型中

validates :email , :email => true

or

或者

 validates :email, :presence => true, 
                :length => {:minimum => 3, :maximum => 254},
                :uniqueness => true,
                :email => true