Search code examples
ruby-on-railsdeviseemail-confirmation

Verify email address


I have followed the RoR tutorial by Michael Hartl, for modeling users, sign in, and sign up. Now I'm in a position where I need to verify that whatever email is given upon login is a real email and not some random string that matches the regex I have on validation.

I know Devise handles that. And I don't want to change the working code I have. How could I use ONLY the email verification feature that Devise has ? (don't want it to do any sign-in, and sessions, and authentication etc for me)

If it's not possible to use Devise this way, how devastating would it be to plug Devise to my Rails user model ?

Thanks !


Solution

  • Devise validates emails with regexp (it is very logical do to this using regexp).

    The regexp used by devise is: (copied from devise code)

      # Email regex used to validate email formats. It simply asserts that
      # an one (and only one) @ exists in the given string. This is mainly
      # to give user feedback and not to assert the e-mail validity.
      mattr_accessor :email_regexp
      @@email_regexp = /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/
    

    You can change this reg exp in devise initializer if you are using devise.

    If you don't need devise, you can implement email validation yourself.

    A very good sample is given in official rails guides, Active Record Validations document.

    class EmailValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
          record.errors[attribute] << (options[:message] || "is not an email")
        end
      end
    end