Moh
Moh

Reputation: 259

password with minimum 6 character doesn't work [rails 4]

I am reading the book of Agile web development with rails 4

in the user model I have a password validation that cannot be less than 6 character

validates :password_digest, length: {minimum: 6}

But actually when I create a new user, it allow me to do it with less than 6. Any suggestions?

Thanks

Upvotes: 2

Views: 1393

Answers (2)

marvelousNinja
marvelousNinja

Reputation: 1510

To be short - you're validating the wrong field. Replace :password_digest with :password.

validates :password, length: { minimum: 6 }

A bit longer explanation here: I've opened a book and looking at Chapter 14 (named 'Task I: Logging In'). Looks like you have users table with columns 'name', 'password_digest' and 'salt'. Samples from the book describe how to hash password, mix it with salt and store result in a database. The point is - your 'password_digest' will be long enough even if you generate this from one letter. You can try it by yourself in irb:

require 'digest'
Digest::SHA2.hexdigest('a') #=> "ca978112ca1bbdcafac231b39a2..."

So, you shouldn't validate length of hashed password. Instead you should validate 'password' attribute itself.

Upvotes: 3

Richard Peck
Richard Peck

Reputation: 76774

Encrypted

You're validating password_digest - this indicates it's the encrypted password?

As mentioned in the comments, unless your form input will be called password_digest, it's likely going to be hashed before the validation is performed, making this value always be over 6 chars

The immediate fix for this (although I'm not sure if it's completely correct) is to validate the "naked" password. This will validate the password as in-putted, not the hashed version:

#app/models/user.rb
Class User < ActiveRecord::Base
     validates :password, length: {minimum: 6}
end

Upvotes: 2

Related Questions