Validating Registration

If you look at the User model that Devise created, you can see that a Devise-provided method named devise is being used. This is how you can control the behaviors Devise uses for registration and authentication on a per-model basis. Note the :validatable symbol in the list.

2_bootstrap-login/50-validations/shine/app/models/user.rb
 class​ User < ApplicationRecord
  devise ​:database_authenticatable​,
 :registerable​,
 :recoverable​,
 :rememberable​,
 :trackable​,
»:validatable
 end

This :validatable module is what we’re interested in. By using this in our model, Devise sets up various validations for the model, namely that the password is at least eight characters and that the email address looks like an email address. These defaults are set in the initializer Devise created when you ran rails generate devise:install.

The initializer, located in config/initializers/devise.rb, has copious documentation about all of Devise’s configuration options. If we search for the string “validatable,” we can find the options we want to change, which are password_length and email_regexp. We’ll change the minimum password length to 10 characters and require that emails end in our company’s domain (which will be example.com).

2_bootstrap-login/50-validations/shine/config/initializers/devise.rb
 # ==> Configuration for :validatable
 config.password_length = 10..128
 config.email_regexp = ​/\A[^@]+@example\.com\z/

Because we changed an initializer, you’ll need to restart your server. Once you do that, if you try to register with a short password or an invalid email, you’ll get an error message, as shown in the following screen:

images/2_bootstrap-login/50-validations/failed-registration.png

Note the unstyled error messages. These errors are produced by the helper method devise_error_messages!. You can override how this works by creating app/helpers/devise_helper.rb and implementing your own devise_error_messages! to output whatever markup you want. The details are on Devise’s wiki[27] and, along with what you just learned about styling alerts with Bootstrap, you should be able to easily make those error messages look great.

This covers the user experience and, because this is implemented using Active Record validations, also covers most typical code paths that might modify the email column in the USERS table. Most, but not all.