Pages

Wednesday, December 3, 2014

Adding Password Complexity Validations To Devise

Here we have a typical Devise user model. What’s new is the password complexity validation.
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
  attr_accessible :email, :password, :password_confirmation, :remember_me,

  validate :password_complexity

  def password_complexity
    if password.present? and not password.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d). /)
      errors.add :password, "must include at least one lowercase letter, one uppercase letter, and one digit"
    end
  end
end
This is exactly like your typical custom validation. The only exception is that it validates the password format only when the password is present. Since the password attribute in a Devise model only exists when you are creating a user, and only when you're updating a user, you can't perform this validation every time.
As for the regex, it uses positive look aheads to check for a lowercase letter, uppercase letter, and a digit. Each of those is required for validation.
If you'd like some more advanced security, you can use the Devise Security Extension which provides the above functionality and a whole lot more.

2 comments:

  1. password.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d). /) = > password.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)./)

    ReplyDelete
  2. I like your post very much. It is very much useful for my research. I hope you to share more info about this. Keep posting ruby on rails online training

    ReplyDelete