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

前端 未结 10 855
刺人心
刺人心 2020-12-13 06:40

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

相关标签:
10条回答
  • 2020-12-13 06:47

    Since the main answer's blog site was down, here is the snippet of code from that site via nice cacher or 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
    
    0 讨论(0)
  • 2020-12-13 06:49
    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

    0 讨论(0)
  • 2020-12-13 06:49

    You can use

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

    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 formatted address 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.

    0 讨论(0)
  • 2020-12-13 06:56

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

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

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

    config.email_regexp = /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
    
    0 讨论(0)
  • 2020-12-13 06:58

    You can take reference from 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

    0 讨论(0)
提交回复
热议问题