Unixersis
Unixersis

Reputation: 33

Ruby on Rails user and password validation

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:

Upvotes: 1

Views: 4591

Answers (2)

zeeshan
zeeshan

Reputation: 11

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

Upvotes: 0

Xullnn
Xullnn

Reputation: 405

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.

Upvotes: 7

Related Questions