Search code examples
ruby-on-railsdeviseruby-on-rails-6

What validations does devise provide out of the box? (and where are they located)


I think devise provides a uniqueness: true validation on User email (although I'm not sure where).

I spot this (approximate) email validation regex in config/initializers/devise.rb

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

As well as a validation on password length in the same file:

  # ==> Configuration for :validatable
  # Range for password length.
  config.password_length = 6..128

Question

Does devise provide any other validations out of the box, and if so, where can I find them?

NB the only reason for wanting to know is so I can write any additional validations in models/user.rb and I want to keep the code DRY.


Solution

  • Unique validations for email are on the database level https://github.com/heartcombo/devise/blob/81bf3ad8c1e3812448ba4588598493c8e80ecf10/lib/generators/active_record/templates/migration.rb#L15

    After running the devise generator and migrations you should see in your schema.rb:

    t.index ["email"], name: "index_users_on_email", unique: true
    

    The initial devise generator will provide these unique indices out of the box:

        add_index :users, :email,                unique: true
        add_index :users, :reset_password_token, unique: true
        # add_index :users, :confirmation_token,   unique: true
        # add_index :users, :unlock_token,         unique: true
    

    Other Devise Validations are listed here https://github.com/heartcombo/devise/blob/81bf3ad8c1e3812448ba4588598493c8e80ecf10/lib/devise/models/validatable.rb#L19-L44