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

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

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

10条回答
  •  Happy的楠姐
    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
    

提交回复
热议问题