1

I have specific requirements for user registration validation of username and password using bcrypt only (no devise!)

I currently have working:

validates :username,
          presence: true,
          length: { minimum: 2, maximum: 15 },
          uniqueness: true

validates :password, 
          presence: true,
          length: { minimum: 10 },

I need:

  • Username:
    1. Can only contain letters, digits, dashes and underscores
  • Password:
    1. Must contain at least one uppercase letter, one special character, one number and one lowercase letter
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
Unixersis
  • 33
  • 1
  • 5

2 Answers2

7

1. For your first need, you could add this to your username validates:

format: { with: /\A[\w-]+\z/, message: "your format requirements" }

2. For your second need, I didn't figure out a regexp for it, you could try adding a customized validation.

First add this validate method to your model:

def password_requirements_are_met
  rules = {
    " must contain at least one lowercase letter"  => /[a-z]+/,
    " must contain at least one uppercase letter"  => /[A-Z]+/,
    " must contain at least one digit"             => /\d+/,
    " must contain at least one special character" => /[^A-Za-z0-9]+/
  }

  rules.each do |message, regex|
    errors.add( :password, message ) unless password.match( regex )
  end
end

Then write this line in your model:

validate :password_requirements_are_met

Thus in your form page, through the object's .errors attribute you could display users the format requirements that they were missing.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
Xullnn
  • 405
  • 3
  • 17
0

second one will work fine. but while updating filed other than password it will fail as password is nil, and throws error nil trying match(regex)

So, you need to run this method only if password in not blank

zeeshan
  • 11
  • 2